3Sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
Notice that the solution set must not contain duplicate triplets.
Constraints:
- 3 <= nums.length <= 3000
- -10^5 <= nums[i] <= 10^5
Example
Input: nums = [-1,0,1,2,-1,-4]
Output: [[-1,-1,2],[-1,0,1]]
Explanation:
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
思路
分析下题干
- 一组结果中元素不能重复使用
- 不能出现相同结果集
那应该需要想到一定按照顺序来,才能保证结果集完整,同时也能忽略相同的值,因为排完序,他们一定是相邻的
[-4,-1,-1,0,1,2]
-4 -> [-1,-1,0,1,2] 取出一个值作为定值,那现在这个问题就变成了Two Sum了
...
-4 -1 -1 0 [1,2] 依次遍历
题解
- 无脑快速AC
public List<List<Integer>> threeSum(int[] nums) {
Arrays.sort(nums);
ArrayList<List<Integer>> result = new ArrayList<>();
int left, right, cur;
for (int i = 0; i < nums.length; i++) {
cur = nums[i];
left = i + 1;
right = nums.length - 1;
// Two Sum II 解法
while (left < right) {
int sum = cur + nums[left] + nums[right];
if (sum > 0)
right--;
else if (sum < 0)
left++;
else {
result.add(Arrays.asList(cur, nums[left], nums[right]));
left++;
// 如果当前left和下一位相等,那就应该跳过下一位,不然下一位也会被当作结果加进来
while (left < right) {
if (nums[left] == nums[left - 1])
left++;
else break;
}
}
}
// 如果当前定值和下一位相等,也需要跳过,不然结果集会相同
while (i < nums.length - 1) {
if (nums[i] == nums[i + 1])
i++;
else break;
}
}
return result;
}
- 优化
public List<List<Integer>> threeSum1(int[] nums) {
Arrays.sort(nums);
ArrayList<List<Integer>> result = new ArrayList<>();
int left, right, cur;
for (int i = 0; i < nums.length; i++) {
cur = nums[i];
if (i != 0 && cur == nums[i - 1])
continue;
left = i + 1;
right = nums.length - 1;
while (left < right) {
int sum = cur + nums[left] + nums[right];
if (sum > 0)
right--;
else if (sum < 0)
left++;
else {
result.add(Arrays.asList(cur, nums[left], nums[right]));
left++;
while (nums[left] == nums[left - 1] && left < right)
left++;
}
}
}
return result;
}
标签:Medium,15,cur,nums,3Sum,++,int,right,left
From: https://www.cnblogs.com/tanhaoo/p/17041168.html