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
  • 相关阅读:
    校内模拟赛 虫洞(by NiroBC)
    校内模拟赛 旅行(by NiroBC)
    P3830 [SHOI2012]随机树
    4358: permu
    【noi.ac】#309. Mas的童年
    P1438 无聊的数列
    2091: [Poi2010]The Minima Game
    LOJ #6074. 「2017 山东一轮集训 Day6」子序列
    LOJ #6068. 「2017 山东一轮集训 Day4」棋盘
    LOJ #6073. 「2017 山东一轮集训 Day5」距离
  • 原文地址:https://www.cnblogs.com/yawenw/p/12343501.html
Copyright © 2011-2022 走看看