标签:des style blog io ar color os sp for
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:
For example, given array S = {-1 0 1 2 -1 -4}, A solution set is: (-1, 0, 1) (-1, -1, 2)
1 public class Solution { 2 public List<List<Integer>> threeSum(int[] num) { 3 List<List<Integer>> resList = new ArrayList<List<Integer>>(); 4 if (num.length<3) return resList; 5 6 Arrays.sort(num); 7 Map<Integer,Integer> numMap = new HashMap<Integer,Integer>(); 8 for (int i=0;i<num.length;i++) 9 if (numMap.containsKey(num[i])) 10 numMap.put(num[i],numMap.get(num[i])+1); 11 else numMap.put(num[i],1); 12 13 int first = 0; 14 int second = -1; 15 while (first<num.length-2){ 16 numMap.put(num[first],numMap.get(num[first])-1); 17 second = first+1; 18 while (second<num.length-1){ 19 numMap.put(num[second],numMap.get(num[second])-1); 20 int left = 0-num[first]-num[second]; 21 if (left>=num[second] && numMap.containsKey(left) && numMap.get(left)>0){ 22 List<Integer> temp = new LinkedList<Integer>(); 23 temp.add(num[first]); 24 temp.add(num[second]); 25 temp.add(left); 26 resList.add(temp); 27 } 28 numMap.put(num[second],numMap.get(num[second])+1); 29 if (left<num[second]) break; 30 while (second< num.length-1 && num[second]==num[second+1]) second++; 31 second++; 32 } 33 numMap.put(num[first],numMap.get(num[first])+1); 34 while (first<num.length-2 && num[first]==num[first+1]) first++; 35 first++; 36 37 } 38 39 return resList; 40 } 41 }
NOTE: There is a way to solve this problem without using hashmap. Practice it!
标签:des style blog io ar color os sp for
原文地址:http://www.cnblogs.com/lishiblog/p/4127609.html