leetcode16 3Sum Closest
Posted yawenw
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于leetcode16 3Sum Closest的主要内容,如果未能解决你的问题,请参考以下文章