【LeetCode OJ 016】3Sum Closest
来源:互联网 发布:mac怎么安装打印机驱动 编辑:程序博客网 时间:2024/05/21 10:41
题目链接:https://leetcode.com/problems/3sum-closest/
题目: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).题意:给定一个数组和一个target数,找出三个数使得他们的和最接近于target。
public class Solution{ public int threeSumClosest(int[] nums, int target) { int length=nums.length; int minNum=Integer.MAX_VALUE; int tempsubNum=Integer.MAX_VALUE; Arrays.sort(nums); for(int i=0;i<length-2;i++) { //略过相同的数 if(i!=0&&nums[i]==nums[i-1]) { continue; } int left=i+1; int right=length-1; while(left<right) { int a1=nums[left]; int a2=nums[right]; int sum=a1+a2+nums[i]; int subNum=Math.abs(sum-target); //当前的和值sum离target更近一点 if(subNum<=tempsubNum) { tempsubNum=subNum; //保存这一步中的sum-target的差值 minNum=sum; } if(sum-target<0) //说明sum<target,要往右移动,使得sum变大才能更接近target left++; else//反之,往左移动 right--; } } return minNum; }}
0 0
- 【LeetCode OJ 016】3Sum Closest
- 【LeetCode OJ 016】3Sum Closest
- LeetCode OJ:3Sum Closest
- LeetCode OJ 3Sum Closest
- LeetCode OJ - 3Sum Closest
- [LeetCode OJ]16. 3Sum Closest
- LeetCode OJ-16-3Sum Closest
- LeetCode OJ - 3Sum、3Sum Closest、4Sum
- LeetCode 016 3Sum Closest
- LeetCode 016 3Sum Closest
- LeetCode 016 3Sum Closest
- [LeetCode]016-3Sum-Closest
- LeetCode 016 3Sum Closest
- LeetCode 016 3Sum Closest
- LeetCode-016 3Sum Closest
- LeetCode OJ算法题(十六):3Sum Closest
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- Spring中Bean的五个作用域
- 关于类微博的timeline的设计思考
- 获取android系统的一些功能
- Android高效加载大图、多图解决方案_LruCache,有效避免程序OOM
- 刨根问底Objective-C Runtime
- 【LeetCode OJ 016】3Sum Closest
- linux设备驱动归纳总结(五):4.写个简单的LED驱动
- java实现单链表反转(遍历方式)
- git与svn区别
- iOS画图的一些笔记CGContextRef
- 首次与python的感想
- JavaScript Number数字类型
- Eclipse下快速打开本地文件插件EasyExplorer
- 字符串数组char[]和字符串指针char*的讨论