LeetCode : 3Sum Closest [java]
来源:互联网 发布:java web架构设计 编辑:程序博客网 时间:2024/05/17 01:26
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).
思路:同上篇博客,稍加变化而已。
import java.util.Arrays;public class Solution { public int threeSumClosest(int[] nums, int target) {if (nums.length < 3) {return 0;}Arrays.sort(nums);int value = nums[0] + nums[1] + nums[2];for (int i = 0; i < nums.length; i++) {if (i >= 1 && nums[i] == nums[i - 1]) {continue;}int j = i + 1;int k = nums.length - 1;while (j < k) {int nowValue = nums[i] + nums[j] + nums[k];if (Math.abs(nowValue - target) < Math.abs(value - target)) {value = nowValue;}if (nowValue > target) {while (k > j && k <= nums.length - 2 && nums[k] == nums[k - 1]) {k--;}k--;} else if (nowValue < target) {while (j < k && j >= 1 && nums[j] == nums[j + 1]) {j++;}j++;} else {return target;}}}return value; }}
1 0
- [LeetCode][Java] 3Sum Closest
- LeetCode : 3Sum Closest [java]
- leetcode 3Sum Closest(Java)
- 3Sum Closest leetcode java
- LeetCode – 3Sum Closest (Java)
- 【leetcode-16】3Sum Closest(java)
- (Java)LeetCode-16. 3Sum Closest
- leetcode-java-16. 3Sum Closest
- 3Sum Closest Leetcode Python Java
- Leetcode 16. 3Sum Closest (Medium) (java)
- [LeetCode-Java]16. 3Sum Closest
- [LeetCode] 16. 3Sum Closest java
- LeetCode: 3 Sum Closest
- leetcode - 3 sum closest
- leetcode 3Sum Closest
- LeetCode: 3Sum Closest
- [Leetcode]3Sum Closest
- Leetcode: 3SUM Closest
- OSI参考模型_20160301
- 好好学习天天向上
- asp.net mvc4使用百度ueditor编辑器
- Laravel学习-三种方式搭建开发环境
- ActionBar之属性详解总结(二)
- LeetCode : 3Sum Closest [java]
- hdoj--1418--抱歉(水题)
- 分区的回收_20160303
- 文本的词条化和向量化
- 基础练习 十六进制转十进制
- 网络多线程
- java.lang.NoClassDefFoundError: org/mybatis/generator/exception/InvalidConfigurationException
- 同名函数及链接过程
- 日本房地产泡沫破裂后的平民生活