how to avoid duplicates in this code?


  • 0
    N

    public List<List<Integer>> fourSum(int[] nums, int target) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    Arrays.sort(nums);

        Map<Integer, Set<Integer>> map = new HashMap<Integer, Set<Integer>>();
        for(int i=0;i<nums.length;i++){
            if(map.containsKey(nums[i])){
                map.get(nums[i]).add(i);
            }else{
                Set<Integer> tempSet = new HashSet<Integer>();
                tempSet.add(i);
                map.put(nums[i], tempSet);    
            }
        }
        
        for(int i=0;i<nums.length-2;i++){
            int j=i+1;
            int k=nums.length-1;
            while(j<k){
                int sum = nums[i] + nums[j] + nums[k];
                if(sum<=target){
                    int diff = target-sum;
                    
                    if(map.containsKey(diff)){
    
                        for(Integer temp: map.get(diff)){
                            
                            if(temp<=i || temp==j || temp==k ) continue;
                            List<Integer> tempResult = new ArrayList<Integer>();
                            tempResult.add(nums[i]);
                            tempResult.add(nums[j]);
                            tempResult.add(nums[k]);
                            tempResult.add(nums[temp]);
                            result.add(tempResult);
                            
                        }
                        int temp = nums[j];
                        j++;
                        while(j<k && nums[j]==temp){
                            j++;
                        }
                        
                    }else{
                        j++;
                    }
                }else{
                    k--;
                }
            }
            
        }
        
        return result;
    }

Log in to reply
 

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