Can anyone tell me why my code exceed time limit?


  • 0
    L
    public List<List<Integer>> threeSum(int[] nums) {
        
        List<List<Integer>> re=new ArrayList<List<Integer>>();
        
        if(nums.length<3) return re;
        
        Arrays.sort(nums);
        
        HashMap<Integer,Integer> num_pos_map=new HashMap<Integer,Integer>(1000); 
        
        for(int i=0;i<nums.length;++i)
            num_pos_map.put(nums[i],i);
        
        int a_last=-10000000;
        int b_last=-10000000;
        for(int i=0;i<nums.length-2;++i){
            for(int j=i+1;j<nums.length-1;++j){
                int a=nums[i];
                int b=nums[j];
                int c=0-a-b;
                
                if(a==a_last&&b==b_last){
                    continue;
                }else{
                    a_last=a;
                    b_last=b;
                }
                
                if( num_pos_map.containsKey(c)&&num_pos_map.get(c)>j ){
                    
                    re.add(Arrays.asList(a,b,c) );
    
                }
                
            }
            
        }
        
        
        return re;
    }

  • 0
    C

    if (i>0)
    if (nums[i]==nums[i-1])
    continue;

    Add this line after the first for loop.This just makes sure that the numbers checked once is not checked again in inner for loop.


Log in to reply
 

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