【18. 四数之和 】
Leetcode算法练习 笔记记录
- 18. 四数之和
18. 四数之和
这题其实和三数之和差不多,相当于同一个板子,具体可以看-> 三数之和或者看灵神讲解b站灵神讲解
public List<List<Integer>> fourSum(int[] nums, int target) {int n = nums.length;Arrays.sort(nums);List<List<Integer>> ans = new ArrayList<>();for (int i = 0; i < n - 3; i++) {//枚举第一个数long x=nums[i];//跳过重复的数if (i > 0 && x == nums[i - 1]) {continue;}//优化1 最小的数都比target大,说明没有目标数组if (x+nums[i+1]+nums[i+2]+nums[i+3]>target){break;}//优化2 加上任意3个数都比目标值小,说明当前x不够大跳过本次if(x+nums[n-3]+nums[n-2]+nums[n-1]<target){continue;}//枚举第二个数for (int j = i + 1; j < n - 2; j++) {long y = nums[j];if (j > i + 1 && y == nums[j - 1]) {continue;}int k = j + 1;int l = n - 1;while (k<l){long s = x + y + nums[k] + nums[l];if (s > target){l--;}else if (s < target){k++;}else{ans.add(new ArrayList<>(Arrays.asList((int)x, (int)y, nums[k], nums[l])));for (k++; k < l && nums[k] == nums[k - 1]; k++) ;for (l--; k < l && nums[l] == nums[l + 1]; l--) ;}}}}return ans;}