This O(N^2) solution can only beats ~7% Java Submissions


  • 0

    I use following solution to solve this problem with 96ms, but it can only beats ~7% java submissions. I didn't see any other more efficient Java solutions in the discussion. Does any body has more efficient solutions? Thanks a lot.

    public class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            Arrays.sort(nums);
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            for (int i = 0; i < nums.length - 2; i++) {
                if (i>0 && nums[i]==nums[i-1]) continue;
                int start = i + 1;
                int end = nums.length - 1;
                while (start < end ) {
                    int expected = 0 - nums[i];
                    if (nums[start] + nums[end] == expected) {
                        result.add(Arrays.asList(nums[i], nums[start], nums[end]));
                        end--;
                        start++;
                        while(start < end && nums[end] == nums[end+1]) end--;
                        while(start < end && nums[start] == nums[start-1]) start++;
                    } else if (nums[start] + nums[end] < expected) {
                        start++;
                    } else {
                        end--;
                    }
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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