LeetCode.16 3Sum Closest
来源:互联网 发布:mac如何打拼音声调 编辑:程序博客网 时间:2024/06/07 08:26
题目:
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).
分析:
class Solution { public int threeSumClosest(int[] nums, int target) { //给定数组,和目标值,返回三个数sum最接近target的结果 //对比值 //关键一步 int result=nums[0]+nums[1]+nums[nums.length-1]; Arrays.sort(nums); for(int i=0;i<nums.length-2;i++){ int low=i+1,high=nums.length-1; while(low<high){ int sum=nums[i]+nums[low]+nums[high]; if(sum==target){ //如果相等,直接放回 return sum; }else if(sum>target){ high--; }else{ low++; } //求最小的 if(Math.abs(sum-target)<Math.abs(result-target)){ //存在更小的 result=sum; } } } return result; }}
阅读全文
0 0
- LeetCode 16: 3Sum Closest
- LeetCode 16: 3Sum Closest
- leetcode 16 3Sum Closest
- [leetcode 16] 3Sum Closest
- Leetcode【16】:3Sum Closest
- [leetcode 16] 3Sum Closest
- [Leetcode] 16 - 3Sum Closest
- leetcode.16----------3Sum Closest
- leetcode 16 3Sum Closest
- leetcode-16 3Sum closest
- LeetCode---(16) 3 Sum Closest
- LeetCode 16 - 3Sum Closest
- leetcode 16 -- 3Sum Closest
- 3Sum Closest - LeetCode 16
- leetcode 16: 3Sum Closest
- Leetcode#16 3Sum Closest
- LeetCode(16) 3Sum Closest
- LeetCode #16 3Sum Closest
- OpenCV编程中调用CUDA时,CMakeLists的编写
- MIPI CSI和DSI接口标准简介
- cf 873 Balanced Substring
- 转自 牛客 1040. 有几个PAT(25)
- 比较三个字符串的大小,最后按从小到大的顺序输出
- LeetCode.16 3Sum Closest
- 【Leetcode-Medium-494】Target Sum
- MIPI DSI协议介绍
- 087 定积分求面积应用习题
- php date函数定义
- BZOJ 1296: [SCOI2009]粉刷匠 dp
- C#面向对象编程(三)
- Ubuntu 16.04系统下以太坊Truffle框架搭建V0.1
- Java 线程池-Executor