博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode16. 3Sum Closest(思路及python解法)
阅读量:2242 次
发布时间:2019-05-09

本文共 732 字,大约阅读时间需要 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.

Example:

Given array nums = [-1, 2, 1, -4], and target = 1.The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

找到三个数的和,使这个和距离target距离最近。

思路和3sum差不多,只不过需要记录一下最短距离即可。

还是先将数组排序,然后利用两个指针去遍历数组。多了一步记录距离的过程,注意使用abs()

class Solution:    def threeSumClosest(self, nums: List[int], target: int) -> int:        nums.sort()        closest=float('inf')                for i in range(len(nums)):            if i!=0 and nums[i]==nums[i-1]:continue            l, r=i+1,len(nums)-1                        while l

 

转载地址:http://ajrbb.baihongyu.com/

你可能感兴趣的文章
flask_migrate
查看>>
解决activemq多消费者并发处理
查看>>
UDP连接和TCP连接的异同
查看>>
hibernate 时间段查询
查看>>
java操作cookie 实现两周内自动登录
查看>>
Tomcat 7优化前及优化后的性能对比
查看>>
Java Guava中的函数式编程讲解
查看>>
Eclipse Memory Analyzer 使用技巧
查看>>
tomcat连接超时
查看>>
谈谈编程思想
查看>>
iOS MapKit导航及地理转码辅助类
查看>>
检测iOS的网络可用性并打开网络设置
查看>>
简单封装FMDB操作sqlite的模板
查看>>
iOS开发中Instruments的用法
查看>>
强引用 软引用 弱引用 虚引用
查看>>
数据类型 java转换
查看>>
"NetworkError: 400 Bad Request - http://172.16.47.117:8088/rhip/**/####t/approval?date=976
查看>>
mybatis 根据 数据库表 自动生成 实体
查看>>
C结构体、C++结构体、C++类的区别
查看>>
进程和线程的概念、区别和联系
查看>>