[LeetCode] and the number of the nearest three --16_3Sum Closest

Today begin formal title LeetCode brush journey, its own programming algorithm capabilities are bad, so I decided to carry on training hard, and a solution found in the code, optimization, and personal understanding, that's all.

Column - [LeetCode]

LeetCode subject classification summary

Here Insert Picture Description

Given an array comprising n integers and a target nums target. Nums identify the three integers, and a target such that their closest. The three numbers and return.

Note: there is only assume that each group enter the only answer.

例如,给定数组 nums = [-121-4], 和 target = 1.

与 target 最接近的三个数的和为 2. (-1 + 2 + 1 = 2).

Problem solution 1:

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        minval = 100000
        nums.sort()
        for i in range(len(nums)):
            left = i + 1
            right = len(nums) - 1
            while left < right:
                val = nums[i] + nums[left] + nums[right]
                if abs(val - target) < minval:
                    minval = abs(val - target)
                    result = val
                if val == target:
                    return target
                if val <= target:
                    left += 1
                else:
                    right -= 1
        return result

Problem solution 2:

We think that the problem-solving approach double pointer, build land rtwo pointers, then traverse nums.

class Solution:
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        result = list()
        nums.sort()
        for i,m in enumerate(nums[0:-2]):
            l, r = i + 1, len(nums) - 1
            if nums[l] + nums[l + 1] + m > target:
                result.append(nums[l] + nums[l + 1] + m)
            elif nums[r] + nums[r - 1] + m < target:
                result.append(nums[r] + nums[r - 1] + m)
            else:
                while l < r:
                    result.append(nums[l] + nums[r] + m)
                    if nums[l] + nums[r] + m < target:
                        l += 1
                    elif nums[l] + nums[r] + m > target:
                        r -= 1
                    else:
                        return target
        result.sort(key=lambda x:abs(x-target))
        return result[0]

We first numssort, then traverse numseach element m.

Sort greatly improved efficiency.

We determine numsthe maximum number of two plus mpost is not less than target, if so, at this time we have no way to find and greater than three, and we need to build a resultarray, and join them. We judge numsthe smallest two numbers plus mpost is not greater than target, if so, at this time we have no way to find three smaller than this and, we must join them and to resultthe.

After sorting by the minimum and maximum values and determines whether there is targetthe same situation, if there is, joined to result, and then to select.

This is the above-described two-step operation pruning operation.

Then for other cases, we then follow before the idea can be processed directly and join resultin, but there is no separate treatment for the minimum distance. Finally, and as long as we take targetthe most recent value to (this policy to the sortfunction).

By the absolute value of the size resultsorting, you can select the smallest is the final result.

Here Insert Picture Description
As it can be seen by the results of several experiments in the best possible 48ms, more than 99.8% of the people.

Reference article

Guess you like

Origin blog.csdn.net/TeFuirnever/article/details/94444437