【LeetCode】3Sum Closest
来源:互联网 发布:硬笔入门字帖 知乎 编辑:程序博客网 时间:2024/06/05 20:59
题目
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).
解答题目要求找出数组中三个元素相加的和最接近目标值,然后返回这三个数的值。
先对数组进行排序,然后固定第一个数,第二、三个数在数组前后移动,求出三个数之和,并和目标值比较,判断最接近目标值的三个数的和即可,时间复杂度O(n^2),代码如下:
public class Solution{public int threeSumClosest(int[] num,int target){int min=Integer.MAX_VALUE;int result=0;Arrays.sort(num);int len=num.length;for(int i=0;i<len;i++){int j=i+1;int k=len-1;while(j<k){int sum=num[i]+num[j]+num[k];int diff=Math.abs(sum-target);if(diff==0){return sum;}if(diff<min){min=diff;result=sum;}if(sum<=target){j++;}else{k--;}}}return result;}}
---EOF---
0 0
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- LeetCode 3Sum Closest
- [Leetcode] 3Sum Closest
- LeetCode : 3Sum Closest
- LeetCode 3Sum Closest
- [LeetCode] 3Sum Closest
- 【leetcode】3Sum Closest
- [LeetCode]3Sum Closest
- LeetCode-3Sum Closest
- LeetCode:3Sum Closest
- LeetCode | 3Sum Closest
- 【leetcode】3Sum Closest
- Leetcode: 3Sum Closest
- 第十六周 项目二(4) 单词的个数
- 第十六周 转换日期格式
- C++中this指针的用法.
- Cloudera Impala官方文档中文翻译-2(Using Impala to Query HBase Tables)
- Hadoop架构和设计要点
- 【LeetCode】3Sum Closest
- Java集合框架2——迭代器
- Princeton Algorithms: Part 2 [week 5: Substring Search]
- C++的try_catch异常
- 华尔街纪事丨中国人在美国买房的那些事儿
- XMemcached使用
- 陌陌流行,因为异乡人的渴望?
- Mongodb分页优化
- C++虚函数访问权限的改变