1. 程式人生 > >LeetCode:18. 4Sum(Medium)

LeetCode:18. 4Sum(Medium)

res 丟失 src 開始 整數 ati lan light ref

1. 原題鏈接

https://leetcode.com/problems/4sum/description/

2. 題目要求

給出整數數組S[n],在數組S中是否存在a,b,c,d四個整數,使得四個數之和等於目標整數target。請找出所有滿足此條件的四個整數。

技術分享圖片

3. 解題思路

先對nums進行排序,然後采用兩層for循環來確定前兩個數字,最後在第二層for循環中確定後兩個數字。

註意可能存在重復解!!

如下圖所示,對Input先進行排序:[-4, -1, -1,0, 1,2],target = -1

存在兩個“-1”,因此要考慮結果去重。

使用 if (i == 0 || (i > 0 && nums[i] != nums[i - 1]))

來對第一層for循環,即第一個數字去重。

如果對第二層for循環采用同樣的方法去重,很可能導致丟失一個解,返回下圖的錯誤結果。

技術分享圖片

[-4, -1, -1,0, 1,2],綠色表示第一層for循環遍歷到的位置,紅色表示第二層for循環開始的位置。如果使用 if (nums[j] != nums[j-1]) 來去重,就會跳過“-1”。

因此引入一個計數器count,來判斷第二層for循環執行的次數。當count==1,即第二層for循環剛開始一次時,避免“-1”和“-1”的重復誤判。

4. 代碼實現

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FourSum18 {

    public static void main(String[] args) {
        int[] nums = {-1,-3,-2,2,3,-3,0,-4};
        int target = 4;
        List<List<Integer>> res = FourSum18.fourSum(nums, target);
        for (List list : res) {
            System.out.println(list);
        }
    }

    public static List<List<Integer>> fourSum(int[] nums, int target) {
        ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();
        Arrays.sort(nums);  // 對nums進行排序

        for (int i = 0; i < nums.length - 3; i++) {
            int sum1 = target - nums[i];
            if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) {  // 去除遍歷第一個數字時重復的結果
                int count =0;
                for (int j = i + 1; j < nums.length - 2; j++) {
                    /**
                     * 需要判斷遍歷第二個數字存在重復解的可能
                     * 要同時考慮第一次遍歷的位置
                     * 用count計數第二個數遍歷的次數
                     */
                    count++;

                    if (nums[j] != nums[j-1]|| count==1) {  // 去除遍歷第二個數字時重復的結果
                        int sum2 = sum1 - nums[j], l = j + 1, r = nums.length - 1;
                        while (l < r) {
                            if (nums[l] + nums[r] == sum2) {
                                res.add(Arrays.asList(nums[i], nums[j], 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 (sum2 < nums[l] + nums[r]) {
                                while (l < r && nums[r] == nums[r - 1]) r--;
                                r--;

                            } else {
                                while (l < r && nums[l] == nums[l + 1]) l++;
                                l++;
                            }
                        }
                    }
                }

            }
        }
        return res;
    }
}

  

LeetCode:18. 4Sum(Medium)