TLE for last case. Any Suggestions for improvement in code?


  • 0
    D

    public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {

        Arrays.sort(nums);
        List<List<Integer>> ls = new ArrayList<>();
        List<Integer> al = new ArrayList<>();
        for(int i =0;i<nums.length-1;i++)
        {
            for(int j=i+1;j<nums.length;j++)
            {  
                if(j<=nums.length-2)
                { int search =binSearch(j+1,nums.length-1,-(nums[i]+nums[j]),nums);
          
                if(Integer.MAX_VALUE!=search)
                { 
                    
                    al.add(nums[i]);
                    al.add(nums[j]);
                    al.add(search);
                    if(!ls.contains(al)){
                     ls.add(new ArrayList(al));
        
                        
                    }
                     al.clear();
                }
                       
            }
            
        }
        }
        
        
        return ls;
    }
    
    private static int binSearch(int low,int high,int num,int[]nums)
    {
     
        while(low<=high)
        {
            
            int mid = low+(high-low)/2 ;
            
            if(nums[mid]==num)
            return nums[mid];
            else if(nums[mid]>num)
            {
                high=mid-1;
            }
            else
            {
                low=mid+1;
            }
            
        }
        
        return Integer.MAX_VALUE;
        
        
    }
    

    }


Log in to reply
 

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