1. 程式人生 > 其它 >14.LeetCode 三個數和

14.LeetCode 三個數和

這道題 解法是暴力的優化 想清楚 第一個數怎麼求

然後第二 第三個數怎麼求

為什麼先排序呢

因為排序能有可能判斷是否重複

簡單的優化減少了一毫秒的運算時間

 public List<List<Integer>> threedNums(int[] nums) {

        Arrays.sort(nums); // 先排序

        List<List<Integer>> lists = new ArrayList<>();//構建返回容器
        int n = nums.length;
        //                  儘量優化
for (int first = 0; first < n - 2; first++) { // 排重 if (first > 0 && nums[first] == nums[first - 1]) { continue; } int third = n - 1; int target = -nums[first]; // 儘可能優化 for
(int second = first + 1; second < n - 1; second++) { if (second > first - 1 && nums[second] == nums[second - 1]) { continue; } // 第二個數必須是第二個數的左邊 while (second<third&&nums[second]+nums[third]>target){ third
--; } // 符合就存起來 if (nums[second]+nums[third]==target){ ArrayList<Integer> list = new ArrayList<>(); list.add(nums[first]); list.add(nums[second]); list.add(nums[third]); lists.add(list); } } } return lists; }