leetcode_15.三數之和/16.最接近的三數之和
阿新 • • 發佈:2022-04-16
15.三數之和
給你一個包含 n 個整數的陣列 nums,判斷 nums 中是否存在三個元素 a,b,c ,使得 a + b + c = 0 ?請你找出所有和為 0 且不重複的三元組。
注意:答案中不可以包含重複的三元組。
排序 + 雙指標
class Solution { public List<List<Integer>> threeSum(int[] nums) { int n = nums.length; Arrays.sort(nums); List<List<Integer>> ans = newArrayList<List<Integer>>(); // 列舉 a for (int first = 0; first < n; ++first) { // 需要和上一次列舉的數不相同 if (first > 0 && nums[first] == nums[first - 1]) { continue; } // c 對應的指標初始指向陣列的最右端 int third = n - 1; int target = -nums[first]; // 列舉 b for (int second = first + 1; second < n; ++second) { // 需要和上一次列舉的數不相同 if (second > first + 1 && nums[second] == nums[second - 1]) { continue; }// 需要保證 b 的指標在 c 的指標的左側 while (second < third && nums[second] + nums[third] > target) { --third; } // 如果指標重合,隨著 b 後續的增加 // 就不會有滿足 a+b+c=0 並且 b<c 的 c 了,可以退出迴圈 if (second == third) { break; } if (nums[second] + nums[third] == target) { List<Integer> list = new ArrayList<Integer>(); list.add(nums[first]); list.add(nums[second]); list.add(nums[third]); ans.add(list); } } } return ans; } } 連結:https://leetcode-cn.com/problems/3sum/solution/san-shu-zhi-he-by-leetcode-solution/
連結:https://leetcode-cn.com/problems/3sum/
16.最接近的三數之和
排序 + 雙指標
class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int n = nums.length; int best = 10000000; // 列舉 a for (int i = 0; i < n; ++i) { // 保證和上一次列舉的元素不相等 if (i > 0 && nums[i] == nums[i - 1]) { continue; } // 使用雙指標列舉 b 和 c int j = i + 1, k = n - 1; while (j < k) { int sum = nums[i] + nums[j] + nums[k]; // 如果和為 target 直接返回答案 if (sum == target) { return target; } // 根據差值的絕對值來更新答案 if (Math.abs(sum - target) < Math.abs(best - target)) { best = sum; } if (sum > target) { // 如果和大於 target,移動 c 對應的指標 int k0 = k - 1; // 移動到下一個不相等的元素 while (j < k0 && nums[k0] == nums[k]) { --k0; } k = k0; } else { // 如果和小於 target,移動 b 對應的指標 int j0 = j + 1; // 移動到下一個不相等的元素 while (j0 < k && nums[j0] == nums[j]) { ++j0; } j = j0; } } } return best; } } 連結:https://leetcode-cn.com/problems/3sum-closest/solution/zui-jie-jin-de-san-shu-zhi-he-by-leetcode-solution/