Why is my O(N^2) code time limit exceeded?


  • 0
    J

    public class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
    int sum = 0;
    int temp = 0;
    HashSet<Integer> map = new HashSet<>();
    HashSet<List<Integer>> set = new HashSet<>();

        Arrays.sort(nums);
        
        for(int i=0; i<nums.length-1; i++){
            for(int j=nums.length-1; j>i; j--){
                sum = nums[i]+nums[j];
                temp = 0-sum;
                if(map.contains(temp)){
                    set.add(Arrays.asList(nums[i],nums[j],temp));
                }
                else{
                    map.add(nums[j]);
                }
            }
            map.clear();
        }
        List<List<Integer>> result = new ArrayList<>(set);
        return result;
    }
    

    }


  • 0
    J

    311 test cases passed. I just want to use Set class to remove duplicates lists.


Log in to reply
 

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