clean java accepted solution


  • 0
    L

    public class Solution {
    public List<List<Integer>> fourSum(int[] nums, int target) {
    List<List<Integer>> ans = new ArrayList<>();
    Arrays.sort(nums);
    for(int a = 0; a < nums.length - 3; a++){

            if(a-1 >= 0 && nums[a] == nums[a-1]){
                continue;
            }
            for(int b = a+1; b < nums.length - 2; b++){
                
                if(b-1 > a && nums[b] == nums[b-1]){
                    continue;
                }
                int target0 = target - nums[a] - nums[b];
                int lo = b+1, hi = nums.length - 1;
                while(lo < hi){
                    int sum = nums[lo]+nums[hi];
                    if(sum == target0){
                        List<Integer> list = new ArrayList<>();
                        list.add(nums[a]);
                        list.add(nums[b]);
                        list.add(nums[lo]);
                        list.add(nums[hi]);
                        ans.add(list);
                        while(lo+1<nums.length && nums[lo] == nums[lo+1]) lo++;
                        while(hi-1<=0 && nums[hi] == nums[hi-1]) hi--;
                        lo++;
                        hi--;
                    }else if(sum < target0){
                        lo++;
                    }else{
                        hi--;
                    }
                }
            }
        }
        return ans;
    }
    

    }


Log in to reply
 

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