Java Hash Set solution, using hash set to avoid duplicates. Super easy to understand!


  • 0
    P

    Using hash set to avoid duplicates, most of the time it will pass OJ. Although not as fast as other solutions, it's super easy to understand.

    public class Solution {
            public List<List<Integer>> threeSum(int[] nums) {
                    List<List<Integer>> myList= new ArrayList<>();
                    if(nums.length<3||nums==null)
                            return myList;
                    Arrays.sort(nums);
                    Set<List<Integer>> set = new HashSet<>();
    
                    for(int i=0;i<nums.length-2;i++)
                    {
    
                            int left=i+1;
                            int right=nums.length-1;
                            int target=-nums[i];
                            while(left<right)
                            {
                                    if(nums[left]+nums[right]==target)
                                    {
                                            set.add(Arrays.asList(nums[i],nums[left],nums[right]));
                                            left++;
                                            right--;
                                    }
                                    else if(nums[left]+nums[right]>target) right--;
                                    else left++;
                            }
                    }
                    myList.addAll(set);
                    return myList;
    }
    }
    

  • 0
    L

    @pq890831 Good solution but adds the cost of doing an array comparison of size 3 everytime you add an element. It will call the Arrays.equals that will do a index-based comparison everytime you add it to the set. Not super-expensive but perhaps could be avoided.


Log in to reply
 

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