每天一题LeetCode[第十四天]
来源:互联网 发布:淘宝模板怎么用 编辑:程序博客网 时间:2024/06/07 18:25
每天一题LeetCode[第十四天]
3 Sum Closest
Description:
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.For example, given array S = {-1 2 1 -4}, and target = 1.The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
翻译:
给一个整型数组,三个数之和为一组,找到最接近target的一组数之和,并将这个和返回。你可以认为每次输入的数据直邮一个确切答案例子:整型数组 {-1,2, 1,-4} target=1所以最佳答案为 2 因为 -1+2+1=2
解题思路:
- 这一题一开始有点懵逼,后来会想到之前做的3 sum的题目,就大概有了思路了,类似把target =0 的情况 并且最佳条件为result-target 的最小值 从头遍历到尾,每次遍历设置两个指针,分别从头和尾开始。根据满足不同的条件那向中间逼近。很简单,tmpSum
Java代码:
public class Solution { public int threeSumClosest(int [] num, int target){ int result=num[0]+num[1]+num[2]; int tmpSum=0; Arrays.sort(num); for(int i=0;i<num.length-2;i++){ int start=i+1,end=num.length-1; while (start<end){ tmpSum=num[i]+num[start]+num[end]; if(tmpSum>target){ end--; }else if(tmpSum<target){ start++; }else{ return tmpSum; } if(Math.abs(tmpSum-target)<Math.abs(result-target)){ result=tmpSum; } } } return result; }}
提高代码质量就是:积累精美的思路,优质的细节的过程。
0 0
- 每天一题LeetCode[第十四天]
- 每天一题LeetCode [第一天]
- 每天一题LeetCode[第五天]
- 每天一题LeetCode[第三天]
- 每天一题LeetCode[第七天]
- 每天一题LeetCode[第八天]
- 每天一题LeetCode[第九天]
- 每天学习10句英语-第十四天
- 第十四天(类继承·一)
- 第十四天
- 第十四天
- 第十四天
- 第十四天
- 第十四天
- 第十四天
- 第十四天
- 第十四天
- 每天一题LeetCode [第二天]
- 笔记二:进程间的通信(fork、孤儿进程,僵死进程等)
- C++之浅谈继承
- OS X环境下安装MySQL-python
- Android 性能典范:拯救计划
- 一步一步在Windows中使用MyCat负载均衡 上篇
- 每天一题LeetCode[第十四天]
- Android Studio ButterKnife 插件安装使用
- 九、类模板和标准模板库STL(Standard Template Library)
- 基础类(1)
- make 的参数
- Kubernetes 1.2 新功能介绍:Ingress 原理及实例
- 初探hive
- Count the Sheep
- mybatis配置文件