15. 3Sum

Description

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.

Note: The solution set must not contain duplicate triplets.

Solution

Three-pointers, O(n^2) time, O(1) space

先對數組進行排序,注意去重。

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> triples = new ArrayList();
        if (nums == null || nums.length < 3) {
            return triples;
        }
        
        Arrays.sort(nums);
        int i = 0;
        int n = nums.length;
        
        while (i < n - 2) {
            int j = i + 1;
            int k = n - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                if (sum < 0) {
                    ++j;
                } else if (sum > 0) {
                    --k;
                } else {
                    List<Integer> triple = new ArrayList();
                    triples.add(Arrays.asList(nums[i], nums[j], nums[k]));  // elegant!
                    // exclude duplicate combinations
                    while (++j < k && nums[j] == nums[j - 1]) {};
                    while (j < --k && nums[k] == nums[k + 1]) {};
                }
            }
            while(++i < n - 2 && nums[i] == nums[i - 1]) {};
        }
        
        return triples;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容