Looking for efficient hashmap solution


  • 0
    F
    public class Solution {
    public List<List<Integer>> threeSum(int[] num1) {
        List<List<Integer>> result = new LinkedList<List<Integer>>();
        LinkedList<Integer> path = new LinkedList<Integer>();
        List<Integer> temp = new LinkedList<Integer>();
        if(num1.length<3){
            return result;
        }
        int count=0;
        HashMap< Integer,Integer> h=new HashMap<Integer,Integer>();
        for(int i=0;i<=num1.length-1;i++){
            if(h.get(num1[i])!=null){
            	if(h.get(num1[i])<3){
                h.put(num1[i],h.get(num1[i])+1);
            	}
            }
            else{
                count++;
                h.put(num1[i],1);
                temp.add(num1[i]);
            }
        }
        Integer[] num=temp.toArray(new Integer[temp.size()]);
        Arrays.sort(num);
        int target;
        for(int i=0;i<=count-1;i++){
        	
            for(int k=count-1;k>=i;k--){
                target=0-(num[i]+num[k]);
                if(num[i]==num[k]){
                	if(num[i]==0){
                		if(h.get(num[i])<3){
                        continue;
                    }
                	}
                    if(h.get(num[i])==1){
                        continue;
                    }
                }
                if(num[i]==target){
                    if(h.get(num[i])==1){
                        continue;
                    }
                }
                if(target==num[k]){
                    if(h.get(num[k])==1){
                        continue;
                    }
                }
                if(target<num[i]){
                	continue;
                }
                if(target>num[k]){
                	continue;
                }
                if(h.get(target)!=null){
                    path.add(num[i]);
                    path.add(target);
                    path.add(num[k]);
                    List toadd =new LinkedList(path);
                    result.add(toadd);
                    path.clear();
                }
            }
        }
        return result;
    }
    

    }
    Got my hash map solution here, need suggestions or brand new hash map solution. Thanks!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.