15. 3Sum

My Submissions

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.
For example, given array S = [-1, 0, 1, 2, -1, -4],A solution set is:[ [-1, 0, 1], [-1, -1, 2]]

Hide Company Tags
Amazon Microsoft Bloomberg Facebook Adobe Works Applications
Hide Tags
Array Two Pointers
Hide Similar Problems
(E) Two Sum (M) 3Sum Closest (M) 4Sum (M) 3Sum Smaller

/*思路: The idea is to sort an input array and then run through all indices of a possible first element of a triplet. For each possible first element we make a standard bi-directional 2Sum sweep of the remaining part of the array.
 Also we want to skip equal elements to avoid duplicates in the answer without making a set or smth like that.
*/

 // https://discuss.leetcode.com/topic/8125/concise-o-n-2-java-solution/8
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        
        List<List<Integer>> res = new ArrayList<>();
        for (int i = 0; i < nums.length -2 ; i++) {
          if (i == 0 || ( i > 0 && nums[i] != nums[i-1])) {
                int start = i + 1, end = nums.length - 1, sum = 0 - nums[i];
                while (start < end) {
                     if (sum == nums[start] + nums[end]) {
                        res.add(Arrays.asList(nums[i], nums[start], nums[end]));
                        while (start < end && nums[start] == nums[start+1]) start++;
                        while (start < end && nums[end] == nums[end -1]) end--;
                        start++;
                        end--;
                    } else if (nums[start] + nums[end] < sum) {
                        // improve: skip duplicates
                        while (start < end && nums[start] == nums[start+1]) start++;
                        start++;
                    } else {
                        // improve: skip duplicates
                        while (start < end && nums[end] == nums[end -1]) end--;
                        end--;
                    }
                }    
           }
       
        }
        
        return res;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容