Thinking private school-LeetCode16. The closest sum of three numbers

LeetCode16. The closest sum of three numbers

​ Hello, friends, I am your old friend Tsukahu. Today we will look at a medium-difficulty problem on LeetCode-the nearest sum of thirds problem. I hope that after reading this article, I can bring you some gains.

topic:

​ First, let's take a look at the description of the topic:

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-J1j4JLzT-1593154112609)(https://raw.githubusercontent.com/iszhonghu/Picture-bed/master/img /20200626110631.png)]

analysis

​ For this problem, we first analyze from a simple scenario:

Just find a number

​ The simplest scenario is nothing more than finding the closest sum, then we only need to maintain one variable: best. Best records the current best value, and replaces the best when it is more suitable until the entire array is traversed.

Find the sum of two numbers

​ To be more complicated is to find the sum of the two closest numbers. The simplest idea is to reduce to the previous case, first subtract one value from the target value, and then look for the rest, but this way, the time complexity is not very friendly due to the nested for loop, and there is room for optimization.

​ Now the question is: Where is the room for optimization? How to save this part of space?

​ The problem with the above method is that when we are the first one that is already smaller than the target value, adding a negative value to it is even less likely to be our target. The next step is to expand, when we a+b When it is already less than the target value, it is completely unnecessary to find a value smaller than b to add to a.

  • Ordered array plus double pointer:
    • Then we sort the array first, and then we get an ordered array
    • Then the left and right pointers point to the first and last respectively, add them to get sum, and then compare best and sum which is closer to the target value
    • Then judge whether the sum is larger or smaller than the target value. If it is larger, the right pointer moves to the left, and if it is smaller, the left pointer moves to the right.

Find the sum of three numbers

​ Now that we have the experience of the first two times, then we will transform into finding the sum of two numbers, that is, find a fixed value first, and then double pointer.

Code

public  int threeSumClosest(int[] nums, int target) {
    
    
        // 先将数组排序以便和后续双指针运算
        Arrays.sort(nums);
        int len = nums.length;
        // 赋值默认初始值,
        int best = nums[0] + nums[1] + nums[2];
        int sum = 0;
        // 固定a找b和c
        for (int a = 0; a < len; a++) {
    
    
            // 为了防止重复查找 b=a+1;
            int b = a + 1;
            int c = len - 1;
            while (b < c) {
    
    
                sum = nums[a] + nums[b] + nums[c];
                if (sum == target) {
    
    
                    return sum;
                }
                // 判断是否需要更新最佳值
                if (Math.abs(sum - target) < Math.abs(best - target)) {
    
    
                    best = sum;
                }
                // 判断双指针哪一个需要移动
                if (sum > target) {
    
    
                    c--;
                } else {
    
    
                    b++;
                }
            }
        }
        return best;
    }

At last

  • If you feel that you are rewarded after reading, I hope to give me a thumbs up. This will be my biggest motivation for updating. Thank you for your support.
  • Welcome everyone to pay attention to my official account [java Toka Fox], focus on the basic knowledge of java and computer, and ensure that you will get something after reading it. If you don’t believe me, hit me
  • If you have different opinions or suggestions after reading, welcome to comment and share. Thank you for your support and love.

Guess you like

Origin blog.csdn.net/issunmingzhi/article/details/106969848