解题思路:
需要先弄懂三数之和,思路类似
三数之和:指针 i ,left ,right
四数之和:指针 k ,i ,left ,right(相当于多了一个 k ,多了一个外层 for 循环)
需要注意剪枝操作,因为给的是target,target不一定是正数,所以要额外有值>=0的判断
class Solution {public List<List<Integer>> fourSum(int[] nums, int target) {List<List<Integer>> res = new ArrayList<>();Arrays.sort(nums);for (int k = 0; k < nums.length - 3; k++) {if (nums[k] > target && nums[k] >= 0) break;if (k > 0 && nums[k] == nums[k - 1]) continue;for (int i = k + 1; i < nums.length - 2; i++) {if (nums[k] + nums[i] > target && nums[k] + nums[i] >= 0) break;if (i > k + 1 && nums[i] == nums[i - 1]) continue;int left = i + 1;int right = nums.length - 1;while (left < right) {int sum = nums[k] + nums[i] + nums[left] + nums[right];if (sum > target) right--;else if (sum < target) left++;else {res.add(Arrays.asList(nums[k], nums[i], nums[left], nums[right]));while (left < right && nums[left] == nums[left + 1]) left++;while (left < right && nums[right] == nums[right - 1]) right--;left++;right--;}}}}return res;}
}