311 out 313 Testcases passed , How do I optimize it further?


  • 0
    M
    class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
            List<List<Integer>> list1=new LinkedList<List<Integer>>();
            HashSet<LinkedList<Integer>> list=new HashSet<LinkedList<Integer>>();
            boolean v []=new boolean[nums.length];
            if(nums.length<3){
                return list1;
            }
            for(int i=0;i<nums.length;i++){
                if(map.containsKey(nums[i])){
                    
                }
                else{
                   
                    map.put(nums[i],i);        // mapping the values to the index
                }
            }
            for(int i=0;i<nums.length;i++){
                for(int j=i+1;j<nums.length;j++){
                    
                    int temp=nums[i]+nums[j];           // a+b+c=0 => c=-(a+b)
                    temp=-temp;
                    if(map.containsKey(temp)){
                        int x=map.get(temp);
                        if(i!=x && j!=x){               // Making sure that the same element isn't used
                            LinkedList<Integer> l2=new LinkedList<Integer>();
                            
                            l2.add(nums[i]);
                            l2.add(nums[j]);
                            l2.add(temp);
                            Collections.sort(l2);       
                    
                                list.add(l2);
                            
                        }
                    
                    }
                    }
                }
            for(LinkedList<Integer> x: list){
                list1.add(x);
            }
            return list1;
            }
           
        }
     
    

Log in to reply
 

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