4Sum
https://leetcode.com/problems/4sum/description/
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.
A solution set is:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
Thoughts
和3sum同理,只是要多加一层循环。
Code
class Solution {
public List<List<Integer>> fourSum(int[] nums, int t) {
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length - 1; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int target = t - nums[i] - nums[j];
int l = j + 1, r = nums.length - 1;
while (l < r) {
if (nums[l] + nums[r] < target) {
l++;
} else if (nums[l] + nums[r] > target) {
r--;
} else {
res.add(Arrays.asList(nums[i], nums[j], nums[l], nums[r]));
l++;
r--;
while (l < r && nums[r] == nums[r + 1]) {
r--;
}
while (l < r && nums[l] == nums[l - 1]) {
l++;
}
}
}
}
}
return res;
}
}
Analysis
Errors:
while (l < r && nums[r] == nums[r + 1]) 没写在else里
if (j > 0 && nums[j] == nums[j - 1]) 导致[0,0,0,0]没有执行
忘了sort
时间复杂度O(n^3)
做题耗时:20min
Last updated
Was this helpful?