Java Solution With 3Sum


  • 0
    B
        public List<List<Integer>> fourSum(int[] nums, int target) {
            List<List<Integer>> AllList = new ArrayList<List<Integer>>();
            int i , j, k, t = target;
            Arrays.sort(nums);
            if(nums.length < 4) return AllList;
            for(i = 0; i < nums.length - 3; i++){
                if( i >= 1 && nums[i-1] == nums[i]){
                    continue;
                }
                target = t - nums[i];
                ThreeSum(nums, target, i + 1, AllList);
            }
            return AllList;
        }
        public void ThreeSum(int[] nums, int target, int i, List<List<Integer>> AllList){
            int  j, k, t = i;
            if(nums.length - i < 2) return ;
            for(; i < nums.length - 2; i++){
                if( i > t && nums[i-1] == nums[i]){
                    continue;
                }
                j = i + 1; k = nums.length - 1;
                while(j < k){
                    if(nums[j] + nums[k] + nums[i] < target)
                        j = j + 1;
                    else if(nums[j] + nums[k] + nums[i] > target)
                        k = k - 1;
                    else{
                        List<Integer> list = new ArrayList<Integer>();
                        list.add(nums[t - 1]);
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[k]);
                        AllList.add(list);
                        while(j < k && nums[j] == nums[j+1]) j++;
                        j = j + 1;
                        while(j < k && nums[k] == nums[k-1]) k--;
                        k = k - 1;
                    }
                } 
            }
        }
    }```

Log in to reply
 

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