O(N^2) TLE, but runs fine on "Run Code" for the SAME INPUT in 17 ms and output correct results.


  • 0
    J
    public class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            int c = 0;
            Arrays.sort(nums);
            HashMap<ArrayList<Integer>, Integer> map = new HashMap<>();
            for(int k = 0; k < nums.length; k++){
                for(int i = 0, j = nums.length - 1; i < j;){
                    if(i == k) i++;
                    if(j == k) j--;
                    if(nums[i] + nums[j] + nums[k] == 0){
                        ArrayList<Integer> l = new ArrayList<Integer>();
                        l.add(nums[i]);
                        l.add(nums[j]);
                        l.add(nums[k]);
                        Collections.sort(l);
                        if(!map.containsKey(l)) {
                            map.put(l, 0);
                        }
                        i++;
                        j--;
                    } else if(nums[i] + nums[j] + nums[k] < 0) i++;
                    else j--;
                }
            }
            List<List<Integer>> list = new ArrayList<List<Integer>>(map.keySet());
            Collections.sort(list, new Comparator<List<Integer>>(){
                    public int compare(List<Integer> a1, List<Integer> a2){
                        for(int i = 0; i < 3; i++){
                            if(a1.get(i) < a2.get(i)) return -1;
                            else if(a1.get(i) > a2.get(i)) return 1;
                        }
                        return -1;
                    }
                });
            return list;
        }
    }

Log in to reply
 

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