三数之和

给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。

在三元组(a, b, c),要求a <= b <= c。结果不能包含重复的三元组。
先对数组排序.然后以第一个为基准,两根指针分别从基准元素的后一个和数组最后开始,如果三个数和为0则记录,小于0头指针后移,大于0尾指针前移.

针对去重的问题,每次基准移动到下一个不和当前数字相同的数,每次记录成功后,头指针移动到下一个不和当前元素相同处.

import java.util.ArrayList;
import java.util.Arrays;
public class Solution {
    /**
     * @param numbers : Give an array numbers of n integer
     * @return : Find all unique triplets in the array which gives the sum of zero.
     */
    public ArrayList<ArrayList<Integer>> threeSum(int[] numbers) {
        // write your code here
        Arrays.sort(numbers);
        ArrayList <ArrayList<Integer> >al=new ArrayList();

        for(int i=0;i<numbers.length-2;i++){
            if(numbers[i]>0){
                break;
            }
            if(i>0&&numbers[i]==numbers[i-1]){
                continue;
            }
            int head=i+1;
            int tail=numbers.length-1;
            while(true){
                if(head>=tail){
                    break;
                }else if((numbers[i]+numbers[head]+numbers[tail])==0){
                    ArrayList<Integer> a=new ArrayList<>();
                    a.add(numbers[i]);
                    a.add(numbers[head]);
                    a.add(numbers[tail]);
                    al.add(a);
                    head++;
                    while(numbers[head]==numbers[head-1]){
                        if(head<tail){
                            head++;
                        }else{
                            break;
                        }
                    }
                }else if((numbers[i]+numbers[head]+numbers[tail])<0){
                    head++;
                }else if((numbers[i]+numbers[head]+numbers[tail])>0){
                    tail--;
                }
            }
        }
        return al;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值