Saturday, December 27, 2014

4Sum (LeetCode HashMap)

Question: Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.

Note:
Elements in a quadruplet (a,b,c,d) must be in non-descending order. (ie, a ≤ b ≤ c ≤ d)
The solution set must not contain duplicate quadruplets.
    For example, given array S = {1 0 -1 0 -2 2}, and target = 0.

    A solution set is:
    (-1,  0, 0, 1)
    (-2, -1, 1, 2)
    (-2,  0, 0, 2)

Idea: Use four pointers (i, j, k, l) to represent the quadruplet (a,b,c,d). First sort the array. Then fix i, j and use k, l to maintain a window. If the sum is smaller than the target, move k forward; otherwise move l backward. Remember to skip the duplicated elements.

Time: O(n^3) Space: O(1)

Code:
 public class Solution {  
   public List<String> anagrams(String[] strs) {  
     List<String> result=new ArrayList<String>();  
     if(strs==null||strs.length==0)  
     {  
       return result;  
     }  
     HashMap<String,ArrayList<Integer>> map=new HashMap<String,ArrayList<Integer>>();  
     for(int i=0;i<strs.length;i++)  
     {  
       String sorted=specialSort(strs[i]);  
       if(map.containsKey(sorted))  
       {  
         map.get(sorted).add(i);  
       }  
       else  
       {  
         ArrayList<Integer> tmp=new ArrayList<Integer>();  
         tmp.add(i);  
         map.put(sorted,tmp);  
       }  
     }  
     for(String s:map.keySet())  
     {  
       if(map.get(s).size()>=2)  
       {  
         for(int i:map.get(s))  
         {  
           result.add(strs[i]);  
         }  
       }  
     }  
     return result;  
   }  
   public String specialSort(String s)  
   {  
     HashMap<Character,Integer> map=new HashMap<Character,Integer>();  
     for(char c:s.toCharArray())  
     {  
       if(map.containsKey(c))  
       {  
         map.put(c,map.get(c)+1);  
       }  
       else  
       {  
         map.put(c,1);  
       }  
     }  
     StringBuilder builder=new StringBuilder();  
     for(char c='a';c<='z';c++)  
     {  
       if(map.containsKey(c))  
       {  
         int counter=0;  
         while(counter<map.get(c))  
         {  
           builder.append(c);  
           counter+=1;  
         }  
       }  
     }  
     return builder.toString();  
   }  
 }  


No comments:

Post a Comment