小白试水——leetcode腾讯题库-16.最接近的三数之和(Python解答)

  • 题目16:最接近的三数之和
    • 方法一:
        • 解题思路
        • ==代码实现==
    • 方法二:
        • ==代码实现==
    • 方法三:
        • 解题思路
        • 知识补漏
          • bisect用法:
        • ==代码实现==

题目16:最接近的三数之和

给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。

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

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

方法一:

解题思路

  1. 通过遍历获得所有 nums 数组中三数之和,与 target 放入同一数组中并排序;
  2. 确认 target 在新数组中的位置下标;
  3. 判断其前后是否有元素存在以及与 target 差值大小,进而判断最接近 nums 数组三数之和与 target 最接近相等的三数之和。

代码实现

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        lis = [target]
        for i in range(len(nums)-2):
            for j in range(i+1,len(nums)-1):
                for k in range(j+1,len(nums)):
                    lis.append(nums[i]+nums[j]+nums[k])
        lis = sorted(lis)
        a = lis.index(target)
        if (a < len(lis)-1) and ((lis[a+1]-target) < (target-lis[a-1])) and (a > 0):
            return lis[a+1]
        elif a-1 < 0:
            return lis[a+1]
        else:
            return lis[a-1]

方法二:

代码实现

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums.sort()
        n = len(nums)
        res = float("inf")
        for i in range(n):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            left = i + 1
            right = n - 1
            while left < right :
                cur = nums[i] + nums[left] + nums[right]
                if cur == target:return target
                if abs(res-target) > abs(cur-target):
                    res = cur
                if cur > target:
                    right -= 1
                elif cur < target:
                    left += 1
        return res

方法三:

解题思路

  1. float(‘inf’) = 正无穷;
  2. 排序,遍历,双指针,O( N 2 N^2 N2) 时间复杂度,二分法初始化;
  3. 排序是为了使用双指针,首先遍历得到索引 c,然后计算 c,左指针 i,右指针 j 对应数字之和,如果大于 target,j 向内移动,否则 i 向内移动;
  4. i 的初始值不是 c + 1,是为了减少计算量,用二分法得到一个合理的初始值。

知识补漏

bisect用法:
import bisect
bisect.bisect_left(t,x)    # 在T列表中查找x,若存在,返回x左侧位置
bisect.bisect_right(t,x)
bisect.insort_left(t,x)    # 在T列表中查找X,若存在,插入x左侧;
bisect.insort_right(t,x)

下面是其实现的方法,实际是二分法:

def binary_search(t,x):
    temp = t
    temp.sort()
    low = 0
    mid = 0
    high = len(temp)-1
    while low < high:
        mid = (low+high)/2
        if xt[mid]:
            low = mid+1
        else:
            return mid-1    # 是否等价与bisect_left

代码实现

class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums, r, end = sorted(nums), float('inf'), len(nums) - 1
        for c in range(len(nums) - 2):
            i, j = max(c + 1, bisect.bisect_left(nums, target - nums[end] - nums[c], c + 1, end) - 1), end
            while r != target and i < j:
                s = nums[c] + nums[i] + nums[j]
                r, i, j = min(r, s, key=lambda x: abs(x - target)), i + (s < target), j - (s > target)
        return r

小白试水——leetcode腾讯题库-16.最接近的三数之和(Python解答)_第1张图片

你可能感兴趣的:(Python题库)