Title 18, the four and the number of

I, entitled 1

Here Insert Picture Description

Second, the idea

16 the same title, this is the link

Third, the code

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class T0018 {

    public static void main(String[] args) {

        int[] nums = {1, 0, -1, 0, -2, 2};
        System.out.println( fourSum(nums, 0) );     //[[-2, -1, 1, 2], [-2, 0, 0, 2], [-1, 0, 0, 1]]
    }

    public static List<List<Integer>> fourSum(int[] nums, int target) {

        List<List<Integer>> result = new ArrayList<List<Integer>>();        //结果集

        //对数组排序
        Arrays.sort( nums );

        for ( int m = 0; m < nums.length-3; m++ ){
            for ( int n = m+1; n < nums.length-2; n++ ){

                int l = n+1, r = nums.length-1;

                while ( l < r ){

                    int sum = nums[m] + nums[n] + nums[l] + nums[r];

                    if ( sum > target ){
                        while ( r>0 && nums[r] == nums[--r] );
                    }else if ( sum < target ){
                        while( l < nums.length-1 && nums[l] == nums[++l] );
                    }else{
                        List<Integer> list = new ArrayList<Integer>();
                        list.add(nums[m]);
                        list.add(nums[n]);
                        list.add(nums[l]);
                        list.add(nums[r]);
                        result.add(list);

                        while ( r>0 && nums[r] == nums[--r] );
                        while( l < nums.length-1 && nums[l] == nums[++l] );

                    }
                }

                //在对n进行加一的时候跳过所有相同的数
                while ( n < nums.length-2 && nums[n] == nums[n+1] )
                    n++;
            }

            //在对m进行加一的时候跳过所有相同的数
            while ( m < nums.length-3 && nums[m] == nums[m+1] )
                m++;
        }

        return result;
    }
}

  1. Source: stay button (LeetCode)
    link: https: //leetcode-cn.com/problems/4sum
    copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source. ↩︎

Published 48 original articles · won praise 1 · views 853

Guess you like

Origin blog.csdn.net/weixin_45980031/article/details/104160556