Sum—LeetCode-15 3Sum

问题描述:

Given an array S of n integers, are there elements abc 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]
]
解题思想:固定一个值,就可以转化为两个数和等于指定值,要学会抽象思维,时间复杂度O(n*n),见代码:
public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> resList = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        int pre = Integer.MAX_VALUE;
        for(int i = 0;i < nums.length-2; ++i){
            int target = nums[i] * (-1);
            if(pre != nums[i]){
                List<List<Integer>> tempList = twoSum(nums, i+1, target);
                if(null != tempList){
                    for(List<Integer> list: tempList){
                        List<Integer> temp = new ArrayList<Integer>();
                        temp.add(nums[i]);
                        temp.add(list.get(0));
                        temp.add(list.get(1));
                        resList.add(temp);
                    }
                }

            }
            pre = nums[i];
        }
        return resList;
    }

    public List<List<Integer>> twoSum(int[] nums, int beginIndex, int target){
        List<List<Integer>> resList = new ArrayList<List<Integer>>();
        int end = nums.length - 1;
        int preBeginElem = Integer.MAX_VALUE;
        int preEndElem = Integer.MAX_VALUE;
        while(beginIndex < end) {
            if(nums[beginIndex] + nums[end] > target){
                --end;
            } else if(nums[beginIndex] + nums[end] < target){
                ++beginIndex;
            } else {
                if(nums[beginIndex] != preBeginElem && nums[end] != preEndElem){
                    List<Integer> tempList = new ArrayList<Integer>();
                    tempList.add(nums[beginIndex]);
                    tempList.add(nums[end]);
                    resList.add(tempList);
                }
                preBeginElem = nums[beginIndex];
                preEndElem = nums[end];
                ++beginIndex;
                --end;
            }
        }
        return resList;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bboyzqh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值