Accepted Java answer


  • 2
    M
    public List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        
        int length = nums.length;
        int sum = 0;
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> sublist;
        
        HashSet<List<Integer>> set = new HashSet<List<Integer>>();
        
        for(int i = 0 ; i < length - 3 ; i++){
            for(int j = i + 1; j < length - 2; j++){
                int begin = j + 1;
                int end = length - 1;
                while( begin < end ){
                    sum = nums[i] + nums[j] + nums[begin] + nums[end];
                    if( sum < target ){
                        begin++;
                        while( begin < end && nums[begin] == nums[begin-1] ){
                            begin++;
                        }
                    }
                    else if( sum > target ){
                        end--;
                        while( begin < end && nums[end] == nums[end+1]){
                            end--;
                        }
                        
                    }else{
                        sublist = new ArrayList<Integer>();
                        sublist.add(nums[i]);
                        sublist.add(nums[j]);
                        sublist.add(nums[begin]);
                        sublist.add(nums[end]);
                        //check for duplicates sublist
                        if( ! set.contains( sublist ) ){
                            result.add(sublist);
                            set.add(sublist);
                        }
                        begin++;
                        end--;
                        while( begin < end && nums[begin] == nums[begin-1] ){
                            begin++;
                        }
                        while( begin < end && nums[end] == nums[end+1]){
                            end--;
                        }
                    }
                }
            }
        }
        return result;
        
    }

Log in to reply
 

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