3Sum Closest 找出最接近目标的三元组
来源:互联网 发布:activiti5源码下载 编辑:程序博客网 时间:2024/05/16 08:30
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 问题,之前,我们是要找 = 目标的三元组。现在是接近。
即我们的 “ a + b + c - target ” 是所有数组中的三元组中最小的。
我们在原来的3Sum上进行改动,额外增加两个变量minDif :用来标记当前最小的差距;
和 value变量,用来标记当前的形成最小差距的 a + b + c 的值 (即需要的返回值)。
复杂度:
时间复杂度:O(n^2 )
空间复杂度:O ( 1 )
效率:
代码:
public int threeSumClosest(int[] nums, int target) { Arrays.sort(nums); int minDif = Integer.MAX_VALUE; int value = 0; for (int i = 0; i < nums.length; i++) { if (i > 0 && nums[i] == nums[i - 1]) { continue; } int lo = i + 1; int hi = nums.length - 1; while (lo < hi) { int curVal = nums[i] + nums[lo] + nums[hi]; if (Math.abs(curVal - target) < minDif) { minDif = Math.abs(curVal - target); value = curVal; } if (curVal == target) { return value; } else if (curVal > target) { hi--; } else { lo++; } } } return value; }
1 0
- 3Sum Closest 找出最接近目标的三元组
- LeetCode 16 3Sum Closest 找出最接近指定target的三个数的和
- 找出序列中求和最接近于target的三个数 3Sum Closest
- 16. 3Sum Closest(找出和最接近给定值的三个数)
- 3Sum Closest 3个数字的和等于或者最接近与目标数
- LeetCode 3Sum Closest 最接近目标数的三个数和
- LeetCode 16. 3Sum Closest(最接近的和)
- 3Sum Closest 三个数的和最接近某个值
- 3Sum Closest 三数最接近
- LeetCode 16 3Sum Closest(最接近的3个数的和)
- Leetcode刷题记——16. 3Sum Closest(最接近的三个数的和)
- 3Sum Closest 找3个数使得和最接近的target @LeetCode
- [LeetCode]—3Sum Closest 求数组中三个数之和最接近给定target的组合
- 3Sum 找出数组中的三元组,满足三元组之和为0
- 【LeetCode-面试算法经典-Java实现】【016-3 Sum Closest(最接近的三个数的和)】
- 快速算法入门——基于《算法》3-sum找出所有和为0的三元整数组
- Find the Closest Palindrome:寻找与给定目标大小最接近且尽可能小的回文
- [算法题] 最接近零的子数组和 Subarray Sum Closest
- CPU概念和调度算法
- 技术博客访问量突破100万大关,纪念一下……
- 分布式服务框架 Zookeeper -- 管理分布式环境中的数据
- 卸载loadrunner12.5,安装11.0遇到问题
- 女孩梦中被脱衣发生性关系
- 3Sum Closest 找出最接近目标的三元组
- 80C51单片机指令助记符英文全称及功能
- Solr/SolrCloud SearchHandler详解
- Java 六种异常处理的陋习
- IOS 控件常识
- spring mvc常用的注解:
- Mongodb 的基本操作
- Android ORM 框架之 greenDAO
- cron表达式