3 Sum

題目

Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

給出一個有n個整數的數組S,在S中找到三個整數a, b, c,找到所有使得a + b + c = 0的三元組。

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

樣例

For example, given array S = [-1, 0, 1, 2, -1, -4],
A solution set is:
[
[-1, 0, 1],
[-1, -1, 2]
]

解題思路

這道題,用兩個指針 Two Pointers的方式做會比較容易理解,此時的算法時間復雜度是O(n^2)。
要注意的地方有兩個。
一是要注意提前給數組排序,用

Arrays.sort();

的方式就可以實現,這個排序是用快速排序的方式,時間復雜度是O(nlogn);
二是要注意由于題目中專門要求了要unique的結果,所以要排除掉相同的狀況。
具體代碼如下:

public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        
        for (int i = 0; i < nums.length; i++) {
            // skip the same result
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int left = i + 1, right = nums.length - 1;
            while (left < right) {
                List<Integer> temp = new ArrayList<Integer>();
                if (nums[left] + nums[right] + nums[i] == 0) {
                    temp.add(nums[i]);
                    temp.add(nums[left]);
                    temp.add(nums[right]);
                    res.add(temp);
                    // skip the same result
                    while (left < right && nums[left] == nums[left + 1]) {
                        left++;
                    }
                    // skip the same result
                    while (left < right && nums[right] == nums[right - 1]) {
                        right--;
                    }
                    left++;
                    right--;
                } else if (nums[left] + nums[right] + nums[i] < 0) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return res;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容