Leetcode #16 3Sum Closest 找3数之和最接近 解题小节
来源:互联网 发布:淘宝cvv技术 编辑:程序博客网 时间:2024/04/29 19:59
1 题目理解
昨晚上光顾着吃深夜泡面,忘了更新了。。所以这一更就算是补上昨天的,今天的另算。
这道题和 Leetcode #15 3Sum 三数之和 解题小节 很像,区别是#15是要三数之和等于目标值,这题是最接近就可以
做法其实都一样,大家可以点进去看,
也是选择一个基准,然后设立头部和尾巴,向中间靠拢
唯一的不同就是:时刻判断是否出现最接近值!
2 原题
3Sum Closest
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).
3 AC解
我是复制上一题的代码。。哈哈
public class Solution { /** * 其实就是直接复制上一题了 * */ public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int i,j,k,result=0,reserve; int min=Integer.MAX_VALUE; for(i=0;i<nums.length-2;i++){ j=i+1; k=nums.length-1; reserve=target-nums[i]; while(j<k){ if(Math.abs(reserve-nums[j]-nums[k])<min){ result=nums[i]+nums[j]+nums[k]; min=Math.abs(reserve-nums[j]-nums[k]); } if(nums[j]+nums[k]<reserve){ j++; } else{ k--; } } } return result; }}
0 0
- Leetcode #16 3Sum Closest 找3数之和最接近 解题小节
- Leetcode #15 3Sum 三数之和 解题小节
- [LeetCode]—3Sum Closest 求数组中三个数之和最接近给定target的组合
- 3Sum Closest 三数最接近
- LeetCode 16 3Sum Closest 找出最接近指定target的三个数的和
- 3Sum Closest从数列中找到三个数之和最接近给定值
- [LeetCode] 3Sum Closest 最近的三数之和 Python
- 3Sum Closest 找3个数使得和最接近的target @LeetCode
- leetcode(16) 3Sum Closest解题报告
- LeetCode 3Sum Closest 最接近目标数的三个数和
- 最接近3数之和
- LeetCode | 3Sum Closest(找到三个数使其和与target最接近)
- Leetcode刷题记——16. 3Sum Closest(最接近的三个数的和)
- Leetcode #18 4Sum 四数之和 解题小节+K-Sum思想
- 3Sum 数组找3数之和为0 @LeetCode
- 3Sum Closest 三个数的和最接近某个值
- LeetCode 16. 3Sum Closest(最接近的和)
- 【LeetCode】3Sum Closest 解题报告
- Linux静态库和动态库的设计
- Starting MySQL... ERROR! The server quit without updating PID file (/mydata/data/t1.pid).
- 数据分析入门
- 线性表
- 数据挖掘---Kmeans算法
- Leetcode #16 3Sum Closest 找3数之和最接近 解题小节
- 设计模式之外观模式
- nyoj21 三个水杯 (BFS)
- java程序中比较常见的四种判断是否为空的性能优化比较
- Java中构造函数重构+数组小练习
- HttpClient使用详解
- 【摘录+总结】Android动画之Tween动画 (渐变、缩放、位移、旋转)
- 计算机网络常识
- 关于一些基础的Java问题的解答(五)