15. 3Sum

Given an array nums of n integers, are there elements a, b, c in nums 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.

Example:

Given array nums = [-1, 0, 1, 2, -1, -4],

A solution set is:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

Solution

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);          //排序
       
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++){
            if (i > 0 && nums[i] == nums[i-1])    continue;       //跳过重复答案
            int j = i + 1;
            int k = nums.length - 1;
            int target = -nums[i];
            while (j < k){
                int sum = nums[j] + nums[k];
                if (sum == target){
                    result.add(Arrays.asList(nums[i], nums[j], nums[k]));
                    j++;
                    k--;
                    while (j < k && nums[j] == nums[j-1])   j++;    //跳过重复答案
                    while (j < k && nums[k] == nums[k+1])   k--;    //跳过重复答案
                }else if (sum > target){
                    k--;
                }else if (sum < target){
                    j++;
                }
                
            }
        }
        return result;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,452评论 0 10
  • Description: Given an array S of n integers, are there el...
    CharlieGuo阅读 216评论 0 1
  • 电影《黑天鹅》完美的融合了心理,艺术和惊悚元素,一场无疯魔不成活的演绎,最完美的表演是成为了角色本身。妮娜一角由哈...
    不三的婆娑大梦阅读 2,828评论 16 31
  • 噗,宅在家吃个晚饭都还被寿星妈吐槽:“对了,2014年你都干了些啥?好像都没好结果吧。”我跟你什么仇什么怨啊,最后...
    詹珂珂阅读 809评论 3 7
  • 转眼间,我已经离开学校快两年了,一年前出走家园,想着赤手空拳在异地打拼出一片天空,时间匆匆,一个人在异地希望最多...
    进击的小丸子阅读 127评论 0 0