10 Line Java Code using HashSet/Map. Super Easy to Understand.


  • 0
    R
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> toreturn = new LinkedList<List<Integer>>();
        HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
        HashSet<List<Integer>> check = new HashSet<List<Integer>>();
        for (int i = 0; i < nums.length; i++)   hm.put(nums[i], i);
        for (int i = 0; i < nums.length - 1; i++)
            for (int j = i + 1; j < nums.length; j++)
                if(hm.get(-nums[i]-nums[j]) != null && check.add(Arrays.asList(nums[i], nums[j])) && hm.get(-nums[i]-nums[j]) > j)
                    toreturn.add(Arrays.asList(nums[i], nums[j], -nums[i]-nums[j]));
        return toreturn;
    }
    
    1. Sort the Array
    2. Add every elements to hashMap.
    3. Nested for loop looks for the third number with three condition
    • sums up to 0
    • no duplicates ( otherwise [1, 1, 1, -2] will return [[1, 1, -2], [1, 1, -2]] )
    • same number not counted twice ( otherwise [0, 0] will return [0, 0, 0] )

Log in to reply
 

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