18. 四数之和 - 力扣(LeetCode)
思路:
- 双指针思想,转换成三数之和,在转换成二数之和
- 先排序,固定一个数a,转换成三数之和
- 再固定一个数b,转换成二数之和
- 再注意不漏和去重
代码:
public List<List<Integer>> fourSum(int[] nums, int target) {//排序Arrays.sort(nums);//返回的数组List<List<Integer>> list = new ArrayList<>();//求数组长度int n = nums.length;//固定ifor(int i = 0; i < n; ){//固定jfor(int j = i+1; j < n;){int left = j+1;int right = n-1;while(left < right){int sum = nums[left]+nums[right];if(sum > (long)target - nums[i] - nums[j]){right--;}else if(sum < (long)target - nums[i] - nums[j]){left++;}else{list.add(Arrays.asList(nums[i],nums[j],nums[left],nums[right]));//保证不漏,继续寻找left++;right--;//去重nums[left-1]和nums[left]while(left < right && nums[left] == nums[left-1]){left++;}//去重nums[right]和nums[right+1]while(left < right && nums[right] == nums[right+1]){right--;}}} //对nums[j]去重j++;while(j < n && nums[j] == nums[j-1]){j++;}}//对nums[i]去重i++;while(i < n && nums[i] == nums[i-1]){i++;}}return list;}