LeetCode 16. 3Sum Closest
来源:互联网 发布:人工智能概念的提出 编辑:程序博客网 时间:2024/05/18 16:13
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).
Subscribe to see which companies asked this question.
和
public class Solution { public int threeSumClosest(int[] nums, int target) { long min = Integer.MAX_VALUE; int len = nums.length; Arrays.sort(nums); for(int i=0;i<len-2;i++){ if(i>0&&nums[i]==nums[i-1])continue; int j = i + 1; int k = len - 1; while(j<k){ int value = nums[i]+nums[j]+nums[k]; int n = Math.abs(value-target); if(n==0){ return value; } int m = value-target; if(n<Math.abs(min-target)){ min = value; while(j<k&&nums[j]==nums[j+1]){ if(m<0)j++; else break; } while(j<k&&nums[k]==nums[k-1]){ if(m>0)k--; else break; } } if(m>0){ k--; } else{ j++; } } } return (int)min; }}
前面的题类似,变成求三个值的和最接近给定值,并返回这个和,整体思路和3sum一致,而且不需要查重简化了题目。
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
- MVC间的通信(附代码)
- tensorflow自学之前的bigpicture
- Android应用程序管理系列(一)——管理对象封装概述
- TensorFlow实战
- JavaWeb 05 Web应用路径问题【绝对路径和相对路径】
- LeetCode 16. 3Sum Closest
- [人工智能技术]技术实战札记
- Android应用程序管理系列(二)——PackageManager 包管理者
- KVO&KVC
- Android应用程序管理系列(三)—— ApplicationInfo
- 153.n1-导航页下方移动的小圆点
- 袁萌浅谈C919大飞机(三)
- 哈夫曼树和哈夫曼编码
- POJ 3320 · Jessica's Reading Problem【尺取法】