当前位置:网站首页>[leetcode 16] sum of three numbers
[leetcode 16] sum of three numbers
2022-06-30 11:01:00 【Salmon_ lee】
Thinking of this topic : Sort + Double pointer . Less contact before , So here's a record .
If you want to achieve better time complexity , Pruning here is necessary .
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
n = len(nums)
best = int(1e6)
for i in range(n - 2):
if i >= 1 and nums[i] == nums[i-1]:
continue
left, right = i + 1, n - 1
##################### Pruning optimization ####################
if nums[i] + nums[left] + nums[left+1] > target:
right = left + 1
if nums[i] + nums[right-1] + nums[right] < target:
left = right - 1
###################################################
while left < right:
sums = nums[i] + nums[left] + nums[right]
if abs(best - target) > abs(sums - target):
best = sums
if sums == target:
return sums
elif sums < target:
left += 1
else:
right -= 1
return best边栏推荐
猜你喜欢

matplotlib 笔记: contourf & contour

Google 辟谣放弃 TensorFlow,它还活着!

第一届中国数字藏品大会即将召开

历史上的今天:微软收购 PowerPoint 开发商;SGI 和 MIPS 合并

8行代码实现快速排序,简单易懂图解!

煥發青春的戴爾和蘋果夾擊,兩大老牌PC企業極速衰敗

WireGuard简单配置

Voir le changement technologique à travers la Légion Huawei (5): Smart Park

Deep dive kotlin synergy (18): hot and cold data flow

在IPhone12的推理延迟仅为1.6 ms!Snap等详析Transformer结构延迟,并用NAS搜出移动设备的高效网络结构...
随机推荐
Q-Learning笔记
Classic interview question: responsible modules, how do you design test cases for these function points? [Hangzhou multi surveyors] [Hangzhou multi surveyors \wang Sir]
iptables目标TPROXY
sublist3r报错解决
When does the database need to use the index [Hangzhou multi surveyors] [Hangzhou multi surveyors _ Wang Sir]
Deep dive kotlin synergy (18): hot and cold data flow
Review of mathematical knowledge: curve integral of the second type
Google 辟谣放弃 TensorFlow,它还活着!
LVGL 8.2 Image
Dell et Apple, deux entreprises de PC établies, se sont effondrées rapidement
历史上的今天:微软收购 PowerPoint 开发商;SGI 和 MIPS 合并
200000 bonus pool! [Alibaba security × ICDM 2022] the risk commodity inspection competition on the large-scale e-commerce map is in hot registration
The first China Digital Collection conference will be held soon
LVGL 8.2 menu from a drop-down list
SQL必需掌握的100个重要知识点:创建和操纵表
透過華為軍團看科技之變(五):智慧園區
基于HAL库的LED驱动库
Machine learning interview preparation (I) KNN
Double-DQN笔记
腾讯云数据库工程师能力认证重磅推出,各界共话人才培养难题