LeetCode16
来源:互联网 发布:山寨网络机顶盒 编辑:程序博客网 时间:2024/05/22 15:37
【题目】
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.
【思路】
很显然与第15题相关,查找方法也与15题差不多,只是要判断当前组合是否比之前所有组合中,与目标值差最小的一组哪一组更符合需求,决定是否替换即可。
【Java代码】
public class Solution_16_3Sum_closest {public int threeSumClosest(int[] nums, int target){Arrays.sort(nums);int result = nums[0] + nums[1] + nums[2];for(int i = 0 ; i < nums.length - 2 ; i++){int start = i+1, end = nums.length - 1;while(start < end){int curr = nums[i] + nums[start] + nums[end];if(curr < target)start++;else if(curr > target) end--;elsereturn target;if(Math.abs(target - result) > Math.abs(target - curr))result = curr;}}return result;}}
【大佬】
该题第一名的大佬,是直接复用了第15题的代码,以目标为中心,向+1 和 -1 两个方向,逐一判断是否存在三个数的和等于当前新的目标值,如果有,就返回该目标值即可。
阅读全文
0 0
- leetcode16
- LeetCode16
- leetcode16.cloneGraph
- [LeetCode16]Climbing Stairs
- [LeetCode16]3Sum Closest
- LeetCode16:3Sum Closest
- leetcode16 3Sum Closest
- LeetCode16:3Sum Closest
- [LeetCode16]3Sum Closed
- LeetCode16. 3Sum Closest
- leetcode16.3SumClosest
- leetcode16:3Sum Closest
- Leetcode16. 3Sum Closest
- leetcode16~3Sum Closest
- LeetCode16. 3Sum Closest
- leetcode16. 3Sum Closest
- leetcode16. 3Sum Closest
- leetcode16. 3Sum Closest
- Climbing Stairs
- C++并发编程框架Theron(5)——File reader(1)
- 兄弟郊游问题
- JavaScript基础(十) -- 设计模式
- 整理java7中几种常见同步辅助类-Exchanger
- LeetCode16
- JDBC之利用反射技术将查询结果封装为对象
- C++使用初始化列表提高效率
- swift3.0 MD5加密源码
- 函数式编程
- blender里一些不认识的英语单词
- 国王的魔镜
- Linux安装sublime
- 配置JDK