LeetCode第15題:三數之和
一起養成寫作習慣!這是我參與「掘金日新計劃 · 4 月更文挑戰」的第13天,點擊查看活動詳情。
題目描述
給你一個包含 n 個整數的數組 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有和為 0 且不重複的三元組。
注意:答案中不可以包含重複的三元組。
示例 1:
輸入:nums = [-1,0,1,2,-1,-4]\ 輸出:[[-1,-1,2],[-1,0,1]]
示例 2:
輸入:nums = []\ 輸出:[]
示例 3:
輸入:nums = [0]\ 輸出:[]
提示:
0 <= nums.length <= 3000\ -105 <= nums[i] <= 105
思路
一開始看這個題目,些許懵逼,看了一些大佬的題解,才得到了好的思路,首先要定義一下臨時數組來存儲結果,對傳入的數組進行排序,排序後,開始進行數組的遍歷,如果當前值大於0,直接跳出當前,因為此次必然會大於0,再進行下次查找,如果當前值給前一個值相等,説明該數字重複,會導致結果重複,所以就需要去跳過這個數。在考慮一下後續計算,如果當前數跟前後的數都相等,應該跳過去移位進行計算。
代碼
public static List<List<Integer>> threeSum(int[] nums) {
//定義臨時列表存儲結果
List<List<Integer>> ans = new ArrayList<>();
//獲取數組長度
int len = nums.length;
//小於三?沒法玩,返回空的數組給他
if (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) {
//進行計算,如果為0,則代表已經找到了
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 {
R--;
}
}
}
return ans;
}
```
public static void main(String[] args) {
int[] arr = {-1, 0, 1, 2, -1, -4};
List> lists = threeSum(arr);
Object[] objects = lists.toArray();
System.out.println(Arrays.toString(objects));
int[] arr1 = {-1, 0, 1, 2, -1, -4,-5,6};
List> lists1 = threeSum(arr1);
Object[] objects1 = lists1.toArray();
System.out.println(Arrays.toString(objects1));
}
```
運行結果 \ [[-1, -1, 2], [-1, 0, 1]] \ [[-5, -1, 6], [-1, -1, 2], [-1, 0, 1]]
總結
這個三數之和還是蠻難的,一開始是真的想不到咋做,都是看了大佬們的題解,進行提取來完成,還得繼續加油學習。