LeetCode ThreeSum

题目描述:https://oj.leetcode.com/problems/3sum/

题目大意:给定一个数组,找出其中所有的(a,b,c)三元组,a+b+c=0且a<=b<=c,且三元组不能有重复。对数组排序,先确定a,b,再在剩下的元素中二分查找-a-b。


package Tree_Sum;
import java.util.*;
public class Solution{
	class Triplets{
		int a,b,c;
		Triplets(int a,int b,int c){
			this.a = a;
			this.b = b;
			this.c = c;
		}
		public int hashCode(){
			return this.a*100+this.b*10+this.c;
		}
		public boolean equals(Object o){
			Triplets tri = (Triplets)o;
			return (tri.a==this.a && tri.b==this.b && tri.c==this.c);
		}
	}
	
	
    public List<List<Integer>> threeSum(int[] num) {
        Arrays.sort(num);
        LinkedList<List<Integer>> ans = new LinkedList<List<Integer>>();
        HashSet<Triplets> set = new HashSet<Triplets>();
        for(int i = 0;i<num.length;i++){
        	for(int j=i+1;j<num.length;j++){
        		int index=Arrays.binarySearch(num, j+1, num.length, -num[i]-num[j]);
        		if(index>=0){
        			Triplets tri = new Triplets(num[i],num[j],num[index]);
        			if(!set.contains(tri)){
        				set.add(tri);
        				List<Integer> temp = new LinkedList<Integer>();
        				temp.add(num[i]);
        				temp.add(num[j]);
        				temp.add(num[index]);
        				ans.add(temp);
        			}
        		}
        	}
        }
    	return ans;
    }
	public static void main(String[] args) {
		int[] num = new int[]{-1,0,1,2,-1,-4};
		List<List<Integer>> ans = new Solution().threeSum(num);
		for(List<Integer> list:ans){
			for(Integer i:list)
				System.out.print(i+" ");
			System.out.println("");
		}
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值