Array of algorithms — sum of three numbers


Sum of three numbers

difficultysecondaryArray of algorithms -- sum of three numbers

Here is an array of N integersnums, judgmentnumsAre there three elements a, B, C in a such that a + B + C = 0? Please find all triples that satisfy the condition and do not repeat.

be careful:The answer cannot contain duplicate triples.


Given array nums = [- 1, 0, 1, 2, – 1, – 4],

The set of triples meeting the requirements is:

[[-1, 0, 1],[-1, -1, 2]]

You can take a look at this before you look at itSum of two numbers

When encountering the sum of the three numbers, the first thought is that sincea + b = c, soa + b = -cI was thinking,Can we use this-cbytargetThen iterate through the array and reuse the sum of two methods?The code is as follows:

public List<List<Integer>> threeSum(int[] nums) {
        HashSet<List<Integer>> set = new HashSet<>();
        for(int i = 0;i<nums.length;i++){
            List<List<Integer>> res = twoSum(nums,-nums[i],i);
            if(res != null && res.size() != 0){
                for(List<Integer>  l : res) {
                    //Combine the appropriate number pairs with the current number and remove the duplicate!!!
                    int[] arr = new int[]{nums[i], l.get(0), l.get(1)};
                    Arrays.sort(arr); //De duplication by sorting!!!
                    List<Integer> list1 = new ArrayList<>();
                    if (!set.contains(list1)) {
        List list2 = new ArrayList(set);
        return list2;
    public List<List<Integer>> twoSum(int[] nums, int target ,int j){
        //Sum of all the sum of two for the number of return!!! Note that the incoming standard J should be skipped!!!
        HashSet<Integer> hashSet = new HashSet<>();
        List<List<Integer>> list = new ArrayList<>();
        for(int i = 0;i<nums.length;i++){
            if(i == j){
            if(hashSet.contains(target - nums[i])){
                List<Integer> l = new ArrayList<>();
                l.add(target - nums[i]);
                list.add(new ArrayList<>(l));
        return list;

resultArray of algorithms -- sum of three numbers

Array of algorithms -- sum of three numbers

It’s overtime……. The time complexity of finding the appropriate number pair is O (n ^ 2), and then the duplication is removed by sorting. The overall time complexity is very high

Best ideas

Sort and double pointerArray of algorithms -- sum of three numbers

First of all, because the sum of the three numbers is 0, there is no need to find a subscript,Therefore, the array can be sorted to make the whole regular!In fact, the sum of two numbers can also be sorted with double pointers, but that question is the subscript, and the array cannot be disturbed, so the best way is to use hash table. Once you’ve arranged the order, you can use the above idea, that is, each number astargetAnd then traverse the remaining number to judge!

In fact, there are many skills here, which can be learned through the code carefully

public List<List<Integer>> threeSum1(int[] nums) {
        if(nums == null || nums.length <= 2){
            return new ArrayList<>();
        List<List<Integer>> res_list = new ArrayList<>();
        int len = nums.length;
        int left = -1;
        int right = -1;
        Arrays.sort(nums); //Ranking is the premise!!! Only after it is ordered can the process be accelerated by some conditions
        for(int i = 0;i < len;i++){
            if(nums[i] > 0){
                //If the current position is greater than zero, it means that the following ones are greater than zero. It is impossible to round up three numbers so that a + B + C = 0!
            if(i >= 1 && nums[i] == nums[i -1]){
                //If the current number is equal to the previous number, it means that it is repeated and there is no need to judge after the process!
            left = i + 1; //Start with the next number!
            right = len - 1;
            while(left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    List<Integer> list = new ArrayList<>();
                    //The following two while loops are de duplication processes
                    while (left < right &&nums[left] == nums[left - 1]) {
                    while(left < right && nums[right] == nums[right + 1]){
                        right --;
                }else if(sum > 0){
                    right --;
                    left ++;
        return res_list;

Array of algorithms -- sum of three numbers

This work adoptsCC agreementThe author and the link to this article must be indicated in the reprint