r/javahelp • • Jul 11 '22

LeetCode 3 sum help!!

class Solution {
    
    public List<List<Integer>> threeSum(int[] nums) {
        
        List<List<Integer>> ans = new ArrayList<>();
        
        Set<List<Integer>> fin = new HashSet<>();
        
        for(int i = 0; i < nums.length; i++){
            Map<Integer, Integer> map = new HashMap<>();
            int target = -nums[i];
            
            for(int j = 0; j < nums.length; j++){
                
                if(i == j)
                    continue;
                
                if(map.containsKey(nums[j])){
                    List<Integer> tmp = new ArrayList<>();
                    tmp.add(nums[j]);
                    tmp.add(map.get(nums[j]));
                    tmp.add(nums[i]);
                    Collections.sort(tmp);
                    fin.add(tmp);
                }
                else{
                    map.put(target-nums[j], nums[j]);
                }
            }
        } 
        
        //System.out.println(fin);
        Iterator<List<Integer>> itr = fin.iterator();
        while(itr.hasNext()) {
           ans.add(itr.next());
        }
         
        return ans;
        
    }
}
0 Upvotes

7 comments sorted by

View all comments

0

u/Air-Alert Jul 11 '22

This is my code. I failed the last two test cases with time limit exceeded error every time. I thought my code is O(n^2) which should be fast enough for this problem. Can anyone tell me why my code failed>3?

1

u/DDDDarky Jul 11 '22

If you are getting time limit exceeded, then your code is not probably fast enough. Big O is not a measure of the speed of your code.