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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容