zoukankan      html  css  js  c++  java
  • leetcode16 3Sum Closest

     1 """
     2 Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
     3 Example:
     4 Given array nums = [-1, 2, 1, -4], and target = 1.
     5 The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
     6 """
     7 """
     8 双指针法
     9 """
    10 class Solution1:
    11     def threeSumClosest(self, nums, target):
    12         nums.sort()
    13         res = nums[0] + nums[1] + nums[2]
    14         for i in range(len(nums)-2):
    15             # bug 有了下面这个 对于[0,0,0] 过不去
    16             # if nums[i] == [i+1]:
    17             #     continue
    18             j = i + 1
    19             k = len(nums)-1
    20             while j < k:
    21                 n = nums[i] + nums[j] + nums[k]
    22                 if n == target:
    23                     return n
    24                 if abs(n - target) < abs(res - target):
    25                     res = n
    26                 if n > target:  #!!!终止条件,写的时候没有考虑到
    27                     k -= 1
    28                 elif n < target:
    29                     j += 1
    30         return res
    31 
    32 
    33 """
    34 自己的想法暴力解法,三层循环
    35 超时
    36 """
    37 class Solution2:
    38     def threeSumClosest(self, nums, target):
    39         temp = float('inf')
    40         for i in range(len(nums)):
    41             j = i + 1
    42             for j in range(j, len(nums)):
    43                 k = j + 1
    44                 for k in range(k, len(nums)):
    45                     n = nums[i] + nums[j] +nums[k]
    46                     if abs(n-target) < temp:
    47                         temp = abs(n-target)
    48                         res = n
    49         return res
  • 相关阅读:
    loj6145. 「2017 山东三轮集训 Day7」Easy
    CF1019E Raining season
    CF1261F Xor-Set
    Python笔试——递归算法学习
    Python笔试——贪心算法
    Python笔试——万万没想到抓捕孔连顺
    Python笔试——雀魂启动
    Python学习——正则表达式
    Python笔试——毕业旅行问题
    Python笔试——Stern-Brocot tree
  • 原文地址:https://www.cnblogs.com/yawenw/p/12343501.html
Copyright © 2011-2022 走看看