码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode16

时间:2019-06-29 00:25:01      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:self   diff   pre   for   else   style   sel   span   target   

 1 import sys
 2 class Solution:
 3     def threeSumClosest(self, nums: List[int], target: int) -> int:
 4         n = len(nums)
 5         if n <= 3:
 6             return sum(nums)
 7         nums = sorted(nums)
 8         mindiff = sys.maxsize
 9         minsums = 0
10         for i in range(n-2):
11             j,k = i + 1,n - 1
12             while j < k:
13                 sums = nums[i] + nums[j] + nums[k]
14                 diff = sums - target
15                 if diff == 0:
16                     return target
17                 elif diff < 0:
18                     j += 1
19                 else:
20                     k -= 1
21                 if abs(diff) < mindiff:
22                     mindiff = abs(diff)
23                     minsums = sums
24         return minsums

 

leetcode16

标签:self   diff   pre   for   else   style   sel   span   target   

原文地址:https://www.cnblogs.com/asenyang/p/11105099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!