3Sum

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:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
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)
这道题目脑子没转过来,一直想要用贪心的方式做,然后各种bug,后来转变过来,可以根据target来选择。还有一种是可以用暴力方式做,这种方法一个很烦的地方就是去除重复的子项。自己试过好多中方式,然后发现自己对hashCode方法没有理解彻底,特别在重写的hashcode方法不知道。
 public int hashCode() {
int hashCode = 1;
for (E e : this)
hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());
return hashCode;
}

这个是在AbstractList这个类中重写的方法。所以我们可以用HashSet来排除多余项。具体代码都是网上copy下来的,另一种方法的详细解释在这里[url=http://tech-wonderland.net/blog/summary-of-ksum-problems.html]这里[/url]
暴力方法代码
 public List<List<Integer>> threeSum(int[] num) {
HashSet rs = new HashSet();

int len = num.length;
Arrays.sort(num);
if(len <= 2) return new ArrayList(rs);

for(int i = 0; i < len-2; i++) {
if(num[i] > 0) break;
for(int k = len-1; k > i+1; k--) {
if(num[k] < 0) break;
int ab = num[i] + num[k];
int c = -ab;
int j = bs(c, num, i+1, k-1);
if(j>0) {
ArrayList elem = new ArrayList();
elem.add(num[i]);
elem.add(num[j]);
elem.add(num[k]);
elem.hashCode();
rs.add(elem);
}
}
}
return new ArrayList(rs);
}
int bs(int c, int[] num, int l, int r) {
if(num[l] > c || num[r] < c) return -1;
while(l <= r) {
int m = (l+r)/2;
if(num[m] == c) return m;
else if(num[m] < c) l = m+1;
else r = m-1;
}
return -1;
}


另外的方式
	    public ArrayList<ArrayList<Integer>> threeSum(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (num == null || num.length < 3)
return result;
int n = num.length;
Arrays.sort(num);
for (int i = 0; i < n; i++) {
int target = -num[i];
int p = i + 1, q = n - 1;
while (p < q) {
if (num[p] + num[q] < target)
p++;
else if (num[p] + num[q] > target)
q--;
else {
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(-target);
tmp.add(num[p]);
tmp.add(num[q]);
result.add(tmp);
p++;
q--;
// remove duplicates
while (p < n && num[p] == num[p - 1])
p++;
while (q >= i + 1 && num[q] == num[q + 1])
q--;

}

}
// remove duplicates
while (i < n - 1 && num[i + 1] == num[i])
i++;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值