码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】_3Sum

时间:2015-04-07 11:30:05      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:

  • 外加一层循环,遍历数组所有数,作为第一个数,其他两个与2sum类似,a+b=target结束循环,如果小就a+,如果大就b-
  • 将满足条件的结果(三个数字)放入midresult中,midresult是个链表,将midresult放入hashmap中去重
  • 再将hashmap中取出来放入result中即可

? ?

public class _3Sum {

public static ArrayList threeSum(int[] num) {

Arrays.sort(num);

ArrayList result = new ArrayList();

Map hm = new HashMap();

? ?

for (int firstPos = 0; firstPos < num.length; firstPos++) {

int secPos = firstPos + 1;

int thirdPos = num.length - 1;

while (secPos < thirdPos) {

if (num[firstPos] + num[secPos] + num[thirdPos] == 0) {

ArrayList<Integer> midResult = new ArrayList<Integer>();

midResult.add(num[firstPos]);

midResult.add(num[secPos]);

midResult.add(num[thirdPos]);

hm.put(midResult, false);

secPos += 1;

thirdPos -= 1;

} else if (num[firstPos] + num[secPos] + num[thirdPos] < 0) {

secPos += 1;

} else {

thirdPos -= 1;

}

}

}

Iterator it = hm.entrySet().iterator();

while (it.hasNext()) {

//????????????????????????Entry entry =(Entry) it.next();

//????????????????????????result.add(entry.getKey());

result.add(it.next());

}

return result;

? ?

}

? ?

public static void main(String[] args) {

//????????????????int[] num = { -1, 0, 1, 2, -1, -4,-1,0,1};

int[] num = {0,0,0};

System.out.println(threeSum(num));

}

}

【leetcode】_3Sum

标签:

原文地址:http://www.cnblogs.com/keedor/p/4397741.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!