問題描述
給你一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有滿足條件且不重複的三元組。
注意:答案中不可以包含重複的三元組。
示例:
給定數組 nums = [-1, 0, 1, 2, -1, -4],
滿足要求的三元組集合爲:
[
[-1, 0, 1],
[-1, -1, 2]
]
Related Topics 數組 雙指針
解題方案
思路
- 標籤:數組遍歷
- 首先對數組進行排序,排序後固定一個數 nums[i],再使用左右指針指向 *nums[i]*後面的兩端,數字分別爲 nums[L] 和 nums[R],計算三個數的和 sum 判斷是否滿足爲 0,滿足則添加進結果集
- 如果 *nums[i]*大於 0,則三數之和必然無法等於 0,結束循環
- 如果 nums[i] == nums[i-1],則說明該數字重複,會導致結果重複,所以應該跳過
- 當 sum == 0 時,nums[L] == nums[L+1] 則會導致結果重複,應該跳過,L++
- 當 sum == 0 時,nums[R] == nums[R-1] 則會導致結果重複,應該跳過,R–
- 時間複雜度:O(n^2),n 爲數組長度
代碼
class Solution {
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> ans = new ArrayList();
int len = nums.length;
if(nums == null || len < 3) return ans;
Arrays.sort(nums); // 排序
for (int i = 0; i < len ; i++) {
if(nums[i] > 0) break; // 如果當前數字大於0,則三數之和一定大於0,所以結束循環
if(i > 0 && nums[i] == nums[i-1]) continue; // 去重
int L = i+1;
int R = len-1;
while(L < R){
int sum = nums[i] + nums[L] + nums[R];
if(sum == 0){
ans.add(Arrays.asList(nums[i],nums[L],nums[R]));
while (L<R && nums[L] == nums[L+1]) L++; // 去重
while (L<R && nums[R] == nums[R-1]) R--; // 去重
L++;
R--;
}
else if (sum < 0) L++;
else if (sum > 0) R--;
}
}
return ans;
}
}