LeetCode Day4【数据结构】两数之和,合并两个有序数组
1 Two Sum两数之和
题目
法一
第一次暴力解法代码如下,两个for循环,时间复杂度O(n2):
class Solution {
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int m = 0;
int n = 1;
for(int i = 0; i < len; i++){
for (int j = i + 1; j < len; j++){
if (nums[i] + nums[j] == target){
m = i; n = j;
break;
}
}
}
int[] ans = {m, n};
return ans;
}
}
法二
第二次使用哈希表,时间复杂度O(1),思路和代码如下;
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i< nums.length; i++) {
if(map.containsKey(target - nums[i])) {
return new int[] {map.get(target-nums[i]),i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
- 思路:哈希映射
- 题解
- 由于哈希查找的时间复杂度为 O(1),所以可以利用哈希容器 map 降低时间复杂度
- 遍历数组 nums,i 为当前下标,每个值都判断map中是否存在 target-nums[i] 的 key 值
- 如果存在则找到了两个值,如果不存在则将当前的 (nums[i],i) 存入 map 中,继续遍历直到找到为止
- 如果最终都没有结果则抛出异常
88 Merge Sorted Array合并两个有序数组
题目
解法:直接把nums2合并进nums1,sort排序即可。
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
for (int i = 0; i < n; i++){
nums1[i + m] = nums2[i];
}
//或者也可以用arraycopy来合并数组
//System.arraycopy(nums2,0,nums1,m,n);
Arrays.sort(nums1);
}
}
还有更好的方法,即插入时考虑好排序。题解