Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.0 kB
9
Indexable
Never
class Solution {
    public List<List<Integer>> threeSum(int[] nums) {
        int n = nums.length;

        HashMap<Integer, Integer> hmap = new HashMap<Integer, Integer>();
        Set<List<Integer>> set = new HashSet();
        for(int i=0; i<n; i++){
            hmap.put(nums[i], i);
        }

        for(int i=0; i<n-1; i++){
            while(i!=0 && i<n-1 && nums[i]==nums[i-1]){
                i++;
            }
            for(int j=i+1; j<n; j++){
                int target = -nums[i]-nums[j];
                if(hmap.containsKey(target) && hmap.get(target)!=j && hmap.get(target)!=i){
                    List<Integer> list = new ArrayList<>(Arrays.asList(nums[i], nums[j],
                    target));
                    Collections.sort(list);
                    set.add(list);
                    j++;
                }
                while(j<n && nums[j]==nums[j-1]){
                    j++;
                }
            }
        }

        return new ArrayList<>(set);

    }
}