1. 两数之和 - 力扣(LeetCode) (leetcode-cn.com)
我们可以通过进行一次遍历,首先判断哈希表中是否有(target-nums[i]),有就get(key)返回,没有就将(nums[i],i)作为键值对放入hashmap
class Solution {
public static int[] twoSum(int[] nums, int target) {
HashMap<Integer,Integer> a=new HashMap();
int j=0,k=0;
for(int i=0;i<nums.length;i++){
if(a.get(target-nums[i])!=null){
j=a.get(target-nums[i]);
k=i;
break;
}
a.put(nums[i],i);
}
return new int[]{k,j};
}
}
此时的时间复杂度和空间复杂度都为O(n),假如在时间复杂度要求不高的情况下,对空间有要求,要求常数级空间呢?
我们的一般思路就是两层循环,暴力求解,但是时间复杂度超要求了。我们前面说过,双指针的作用就是将O(n^2)降为O(n)。所以我们应该怎么利用双指针呢?
快慢指针在数组中常用来移动数组元素,模拟删除数组元素,左右指针在有序数组中根据target和左右之和的大小更改左右边界。
显然,我们这道题应该用左右指针,即先排序后双指针。这样时间复杂度是O(nlogn),空间复杂度是O(1)
class Solution {
public int[] twoSum(int[] numbers, int target) {
Arrays.sort(numbers);
int i = 0;
int j = numbers.length - 1;
while (i < j) {
int sum = numbers[i] + numbers[j];
if (sum < target) {
i++;
} else if (sum > target) {
j--;
} else {
return new int[]{i+1, j+1};
}
}
return new int[]{-1, -1};
}
}
2.15. 三数之和 - 力扣(LeetCode) (leetcode-cn.com)
三数之和和两数之和类似,外面套一层for循环,里面用哈希表或者排序后双指针都是可以做的,但是哈希表在时间上可以剪枝优化的地方比较少,所以我们用双指针。
注意看双指针剪枝的地方,这个是重点
class Solution {
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {//最小的大于0,肯定没有解,返回空
return result;
}
if (i > 0 && nums[i] == nums[i - 1]) {//nums[i-1]有的解nums[i]不一定有,但nums[i]有的解nums[i-1]一定有
continue;
}
int left = i + 1;
int right = nums.length - 1;
while (right > left) {
int sum = nums[i] + nums[left] + nums[right];
if (sum > 0) {
right--;
} else if (sum < 0) {
left++;
} else {
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
while (right > left && nums[right] == nums[right - 1]) right--;//剪掉重复的
while (right > left && nums[left] == nums[left + 1]) left++;
right--;
left++;
}
}
}
return result;
}
}
3.18. 四数之和 - 力扣(LeetCode) (leetcode-cn.com)
跟三数之和类似,在外面再套一层for循环
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i - 1] == nums[i]) {
continue;
}
for (int j = i + 1; j < nums.length; j++) {
if (j > i + 1 && nums[j - 1] == nums[j]) {
continue;
}
int left = j + 1;
int right = nums.length - 1;
while (right > left) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum > target) {
right--;
} else if (sum < target) {
left++;
} else {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;
left++;
right--;
}
}
}
}
return result;
}
}