アルゴリズム15.3Sum

1620 ワード

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
The solution set must not contain duplicate triplets.
Example:
Given array nums = [-1, 0, 1, 2, -1, -4], A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]
整数配列を与えます.中にはa、b、cの3つの数と0があります.すべての和が0で異なる3つの数を見つけます.NOTE:解の中に同じ3つの数があってはいけません(つまり繰り返し解があってはいけません);
解:まず配列に順序を付けて、最初から遍歴して、iを最初の数として、それから残りの数の両端から残りの2つの数l、rを探して、それと目標値より大きくて、r--、逆にl++、等しくて、対応する値を記録して、繰り返し値をフィルタします.繰り返しを避けるために、最初の数が同じ場合もフィルタリングします.
コードは次のとおりです.
public List> threeSum(int[] nums) {
    Arrays.sort(nums);
    List> result = new ArrayList<>();
    for (int i = 0; i < nums.length - 2; i++) {
        if (i == 0 || nums[i] != nums[i - 1]) { //            
            int l = i + 1, r = nums.length - 1, sum = 0 - nums[i];
            while (l < r) {
                if (nums[l] + nums[r] == sum) {//       ,     
                    result.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 (nums[l] + nums[r] < sum) {
                    l++;
                } else {
                    r--;
                }
            }
        }
    }
    return result;
}