leetcode 16. 3Sum Closest
来源:互联网 发布:知尖品牌 编辑:程序博客网 时间:2024/05/01 14:45
import java.util.Arrays;//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 static void main(String[] args) {int[] a = {1,1,1,1};int result = threeSumClosest(a,-100);System.out.println(result);}public static int threeSumClosest(int[] nums, int target) { int result = 0; int cha = 1000; Arrays.sort(nums);//先对数组排序 for(int i = 0;i<nums.length-2;i++){//与上一题差不多,遍历数组,从当前元素之后的元素段首尾相加:1(当前),1(首),1,1(尾) int j = i+1; int end = nums.length-1; while(j<end){//首小于尾时循环 if(nums[i]+nums[j]+nums[end] == target){ return target; }else if(nums[i]+nums[j]+nums[end]<target){//根据三数相加与target的差值调整首尾的位置 if(cha>Math.abs(target-nums[i]-nums[j]-nums[end])){ cha = Math.abs(target-nums[i]-nums[j]-nums[end]); result = nums[i]+nums[j]+nums[end]; } j++; }else{ if(cha>Math.abs(target-nums[i]-nums[j]-nums[end])){ cha = Math.abs(target-nums[i]-nums[j]-nums[end]); result = nums[i]+nums[j]+nums[end]; } end--; } } } 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. 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
- 过滤器 拦截器 监听器 简单介绍
- (水)POJ-2393 贪心,生产问题
- ubuntu12.04下unix网络编程apue的配置
- MyEclipse 快捷键
- C 的那点事儿
- leetcode 16. 3Sum Closest
- ubuntu14.04 ibus 输入法框架
- 第13条 类与接口——使类和成员的可访问性最小化
- 【C++】高精度代码运行时间( QueryPerformanceCounter )
- 自己写的一个图片三级缓存的工具类,下载图片使用的是volley和httpUrlConnection相同
- HDU 4135 Co-prime(容斥原理)
- 解决“只能通过Chrome网上应用商店安装该程序”的方法
- 创建dblink语句
- 机器学习实战3:决策树学习笔记(python)