Simple Java code


  • 0
    L

    '''
    public List<List<Integer>> fourSum(int[] nums, int target) {
    List<List<Integer>> results = new ArrayList<List<Integer>>();

        int len = nums.length;
        if (nums == null || len < 4) return results;
        
        Arrays.sort(nums);
        
        for (int i = 0; i < len - 3; i++) {
            
            for (int j = i + 1; j < len - 2; j++) {
                
                int s = j + 1; 
                int e = len - 1;
                
                while (s < e) {
                    int t = nums[i] + nums[j] + nums[s] + nums[e];
                    if (t == target) {
                        results.add(Arrays.asList(nums[i], nums[j], nums[s], nums[e]));
                        do { s++;} while(nums[s] == nums[s-1] && s < e);
                    } else if (t < target) s++;
                    else e--;
                }
                
                while (j + 1 < len && nums[j] == nums[j +1]) j++;
            }
            
            while (i + 1 < len && nums[i] == nums[i + 1]) i++;
        }
        
        return results;
    } '''

Log in to reply
 

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