3Sum_Leetcode_#15

1.题目
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]
]

2.解法
思路:先给nums排序,最大值nums[nums.length - 1]与最小值nums[0]之间的距离为gap,取一个数组countNum用来统计nums[i] - nums[0]出现的次数。以-nums[0]作为基准base,(-nums[0] > 0),取x < base, y > base, x < z < y.找到符合x+y+z=3*base的条件的x,y,z.则x-base,y-base,z-base就是一个解。

时间复杂度为O(N^2)

public class Solution {
    public List<List<Integer>> threeSum(int[] nums){
        List arr = new ArrayList();
        int size = nums.length;
        if(size == 0){
            return arr;
        }
        Arrays.sort(nums);
        int gap = nums[size - 1] - nums[0] + 1;
        int[] countNum = new int[gap];
        for(int i = 0; i < size; i++){
            countNum[nums[i] - nums[0]]++;
        }
        int base = -nums[0];
        if(base < 0 || base >= countNum.length){
            return arr;
        }
        if(countNum[base] >= 3){
            arr.add(new int[]{0, 0, 0});
        }
        //x-base <0, y-base>0,  x<z<y
        for(int x = 0; x < base; x = findNextLtBase(countNum, x)){
            for(int y = countNum.length - 1; y > base; y = findNextGtBase(countNum, y)){
                int z = 3 * base - x - y; 
                if(z == x && countNum[x] >= 2 || z == y && countNum[y] >= 2 || z > x && z < y && countNum[z] >= 1){
                    arr.add(new int[]{x - base, y - base, z - base});
                }
            }
        }

        return arr;
    }

    public int findNextLtBase(int[] countNum, int m){
        for(++m; m < countNum.length; ++m){
            if(countNum[m] > 0){
                return m;
            }
        }
        return m;
    }

    public int findNextGtBase(int[] countNum, int m){
        for(--m; m >= 0; --m){
            if(countNum[m] > 0){
                return m;
            }
        }       
        return m;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值