LeetCode OJ算法题(十六):3Sum Closest
来源:互联网 发布:淘宝买东西怎么拿发票 编辑:程序博客网 时间:2024/06/10 18:09
题目:
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).解法:
与上一篇博客3Sum解法遍历方法相同,唯一需要改变的是在每一次Xi+Xj时,都比较三数和与target的误差,如果误差减小,则更新误差与返回值ret。
不再赘述,直接上代码
import java.util.Arrays;public class No16_ThreeSumClosest {public static void main(String[] args){System.out.println(threeSumClosest(new int[]{0,1,2}, 0));}public static int threeSumClosest(int[] num, int target){if(num.length < 3) return 0;Arrays.sort(num);int ret = num[0] + num[1] + num[num.length-1];int err = ret - target;if(err < 0) err *= -1;int k_pre = num[num.length-1]+1;for(int k=0;k<num.length-2;k++){if(num[k] == k_pre) continue;k_pre = num[k];int i = k+1;int j = num.length-1;while(i<j){if(num[i]+num[j] < target-num[k]){if(err > target-num[k]-num[i]-num[j]){err = target-num[k]-num[i]-num[j];ret = num[k]+num[i]+num[j];}i++;continue;}if(num[i]+num[j] > target-num[k]){if(err > num[i]+num[j]+num[k]-target){err = num[i]+num[j]+num[k]-target;ret = num[k]+num[i]+num[j];}j--;continue;}return target;}} return ret;}}
0 0
- LeetCode OJ算法题(十六):3Sum Closest
- LeetCode OJ:3Sum Closest
- LeetCode OJ 3Sum Closest
- LeetCode OJ - 3Sum Closest
- leetcode 3 sum closest算法
- 【LeetCode OJ 016】3Sum Closest
- 【LeetCode OJ 016】3Sum Closest
- [LeetCode OJ]16. 3Sum Closest
- LeetCode OJ-16-3Sum Closest
- LeetCode OJ - 3Sum、3Sum Closest、4Sum
- leetcode - 3Sum Closest (kSum Closest)
- LeetCode算法题——16. 3Sum Closest
- python写算法题:leetcode: 16. 3Sum Closest
- 【LeetCode算法练习(C++)】3Sum Closest
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- 内存映射与消息应用
- Animation动画效果的实现(一)
- 安卓学习随笔 -- 自定义标题栏
- gloox实现会议服务功能
- 2、数据库入门
- LeetCode OJ算法题(十六):3Sum Closest
- UVa10158 War
- 黑马程序员 学习日记(七)
- phpstorm live edit 功能的使用
- git的windows环境搭建
- mysql limit逻辑分页
- squid介绍及其简单配置
- 使用nginx搭建http代理服务器
- 耿建玲视频总结