当前位置:网站首页>【leetcode 16】三数之和
【leetcode 16】三数之和
2022-06-30 10:34:00 【Salmon_lee】
本题思路:排序 + 双指针。之前较少接触,因此在此记录一下。
若想达到比较好的时间复杂度,这里的剪枝是必需的。
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
##################### 剪枝优化 ####################
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边栏推荐
- 第一届中国数字藏品大会即将召开
- LVGL 8.2 Image
- Ant financial's written test question: what can be quantified in the requirements document? [Hangzhou multi tester] [Hangzhou multi tester \wang Sir]
- 【STL源码剖析】迭代器
- 电化学氧气传感器寿命、工作原理及应用介绍
- 历史上的今天:微软收购 PowerPoint 开发商;SGI 和 MIPS 合并
- MATLAB image histogram equalization, namely spatial filtering
- SQL必需掌握的100个重要知识点:插入数据
- 数学知识复习:第二型曲线积分
- The precision problem of depth texture in unity shader - stepping pit - BRP pipeline (there is no solution, it is recommended to replace URP)
猜你喜欢

Pytorch Notebook. Nn. Batchnorm1d

焕发青春的戴尔和苹果夹击,两大老牌PC企业极速衰败

CSDN blog operation team 2022 H1 summary

Retest the cloud native database performance: polardb is still the strongest, while tdsql-c and gaussdb have little change

智能DNA分子纳米机器人模型来了

时间复杂度与空间复杂度

File sharing server

软件测试工程师面试基础题(应届生和测试小菜必备)最基础的面试题
![[understanding of opportunity -34]: fate is within the light cone](/img/3e/9f5630ba382df7f7ce00705445cef8.jpg)
[understanding of opportunity -34]: fate is within the light cone

China will force a unified charging interface. If Apple does not bow its head, iPhone will be kicked out of the Chinese market
随机推荐
如何解决跨域
pytorch 笔记 torch.nn.BatchNorm1d
Wireguard simple configuration
数据库什么时候需要使用索引【杭州多测师】【杭州多测师_王sir】
历史上的今天:微软收购 PowerPoint 开发商;SGI 和 MIPS 合并
Voir le changement technologique à travers la Légion Huawei (5): Smart Park
单片机 MCU 固件打包脚本软件
Iptables target tproxy
再测云原生数据库性能:PolarDB依旧最强,TDSQL-C、GaussDB变化不大
LVGL 8.2 Simple Image button
吴恩达2022机器学习专项课测评来了!
Review of mathematical knowledge: curve integral of the second type
苹果高管公然“开怼”:三星抄袭 iPhone,只加了个大屏
经典面试题:负责的模块,针对这些功能点你是怎么设计测试用例的?【杭州多测师】【杭州多测师_王sir】...
How can the sports app keep the end-to-side background alive to make the sports record more complete?
WireGuard简单配置
我们公司使用 7 年的这套通用解决方案,打通了几十个系统,稳的一批!
Algorithme leetcode 86. Liste des liens séparés
20万奖金池!【阿里安全 × ICDM 2022】大规模电商图上的风险商品检测赛火热报名中!...
Matplotlib notes: contour & Contour