【LeetCode】016.3Sum Closest
2015-07-03 13:07
363 查看
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">题目:</span>
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).
解答:
双指针问题,将数组排序后,依次遍历,当前值往后的部分的首、尾各放一个指针,进行双指针遍历,找到最接近的值
代码:
public class Solution { public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int ret = nums[0] + nums[1] + nums[nums.length-1]; for(int i=0;i<nums.length-2;i++){ int j=i+1; int k=nums.length-1; int result; while(j<k){ result = nums[i]+nums[j]+nums[k]; if(result == target) return result; if(Math.abs(result-target) < Math.abs(ret-target)) ret = result; if(result < target) j++; else k--; } } return ret; } }
相关文章推荐
- Web API应用架构设计分析(1)
- HDU 3415 Max Sum of Max-K-sub-sequence 最长K子段和
- 常用Web开发语言HttpOnly设置详解
- Oracle常用查看表结构命令
- 数据挖掘算法-Apriori Algorithm(关联规则)
- 黑马程序员——java基础---流程控制、函数、数组
- Ruby(Selenium / Rspec)在Windows 8_64上安装步骤
- 写在第一篇---人生
- 用深度优先搜索找到地图降落点最大的相连块的数目
- 局域网无法访问vmware虚拟机WEB服务器解决办法
- 递归调用与尾调用
- 理论物理极础2. 运动
- dig挖出DNS的秘密
- 八大排序算法
- <c:forEach>
- ASP.NET中处理自定义错误的最佳方式
- git 提交到远程服务器
- MFC添加自定义窗口消息
- mysql对sql中别名引起的Column not found问题
- Distributing iOS Developer Enterprise Program Applications