2019年1月27日星期日

[LeetCode] 18. 4Sum

\(▔▽▔)/
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList<>();
Set<List<Integer>> resultSet = new HashSet<>();
if (nums == null || nums.length < 4) {
return result;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; i++) {
for (int j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int left = j + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
resultSet.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
left++;// Attn!
right--;
} else if (sum > target) {
right--;
} else {
left++;
}
}
}
}
for (List<Integer> solution : resultSet) {
result.add(solution);
}
return result;
}
}
view raw fourSum.java hosted with ❤ by GitHub

没有评论:

发表评论