Easy to understand Java Solution


  • 0
    K
    1. Use 3 pointers - i, low, high
    2. Use Hashset to get unique list.
    3. Use Collections.addAll method to copy from HashSet to ArrayList.
    4. Complexity : O(n2), Time : 78 ms
    public class Solution {
        public List<List<Integer>> threeSum(int[] nums) {
            
            List<List<Integer>> result = new ArrayList<>();
            HashSet<List<Integer>> set = new HashSet<>();
            
            if (nums.length<3) {
                return result;
            }
            Arrays.sort(nums);
            
            for (int i=0; i<nums.length-2; i++) {
                int low = i+1;
                int high = nums.length-1;
                while (low < high) {
                    if (nums[i] + nums[low] + nums[high] == 0) {
                        set.add(Arrays.asList(nums[i], nums[low], nums[high]));
                        low++;
                        high--;
                    } else if (nums[i] + nums[low] + nums[high] < 0) {
                        low++;
                    } else {
                        high--;
                    }
                }
            }
            
            result.addAll(set);
            return result;
            
        }
    }
    

Log in to reply
 

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