数组中寻找三个数之和等于0java实现

class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        //判断参数 
        if(nums.length < 3){
            return result;
        }        
        //首先对数组排序
        Arrays.sort(nums);
        //确定一个数另外两个数字使用双指针的方式来检索
        for(int i = 0;i < nums.length - 2;){
            //另外两个数自行调用双指针函数来解决
            search(nums,i,result);
            //解决完毕之后需要排除重复元素带来的干扰
            int temp = nums[i];
            while(i < nums.length && temp == nums[i]){
                i++;
            }
        }
        return result;
    }

    public void search(int[] nums,int index,List<List<Integer>> result){
        //创建双指针
        int opt1 = index + 1;
        int opt2 = nums.length - 1; 
        //遍历数组元素判断双指针
        while(opt1 < opt2){
            if(nums[opt1] + nums[opt2] < -nums[index]){  
                opt1++;
            }else if(nums[opt1] + nums[opt2] > -nums[index]){
                opt2--;
            }else{
                //添加结果集
                List<Integer> item = new ArrayList<Integer>();
                item.add(nums[index]);
                item.add(nums[opt1]);
                item.add(nums[opt2]);
                result.add(item);
                //排除重复元素带来的影响
                int temp = nums[opt1];
                while(temp == nums[opt1] && opt1 < opt2){
                    opt1++;
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值