|
| 1 | +--- |
| 2 | +layout: post |
| 3 | +category : LeetCode |
| 4 | +tagline: "和最接近k的3个数" |
| 5 | +tags : [LeetCode,面试,和最接近k的n个数] |
| 6 | +--- |
| 7 | +{% include JB/setup %} |
| 8 | + |
| 9 | +<h4 id="3Sum-Closest">3Sum Closest</h4> |
| 10 | + |
| 11 | +>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. |
| 12 | +> |
| 13 | +>Note: |
| 14 | +> |
| 15 | + For example, given array S = {-1 2 1 -4}, and target = 1. |
| 16 | +> |
| 17 | + The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). |
| 18 | + |
| 19 | +解法:和3Sum那题类似,这题还限制了很只有一个解。第一种解法,复杂度`O(n^2logn)`,先对数组进行排序,,确定前两个数,对第三个数使用二分查找。去重,因为已经排过序,相同的数只需确定搜索其中一个即可。 |
| 20 | + |
| 21 | +代码如下: |
| 22 | + |
| 23 | + //{java} |
| 24 | + public class Solution { |
| 25 | + public int threeSumClosest(int[] num, int target) { |
| 26 | + Arrays.sort(num); |
| 27 | + int numl=num.length; |
| 28 | + int close = target-99999; |
| 29 | + for(int i=0;i<numl-2;i++) |
| 30 | + { |
| 31 | + for(int j=i+1;j<numl-1;j++) |
| 32 | + { |
| 33 | + int t = findcloseX(num,j+1,numl-1,target-num[i]-num[j]); |
| 34 | + close=closeX(num[i]+num[j]+t,close,target); |
| 35 | + } |
| 36 | + } |
| 37 | + return close; |
| 38 | + } |
| 39 | + |
| 40 | + public int findcloseX(int num[],int s,int e,int x) |
| 41 | + { |
| 42 | + while(s+1<e) |
| 43 | + { |
| 44 | + int t = num[(s+e)/2]; |
| 45 | + if(t>x) |
| 46 | + { |
| 47 | + e=(s+e)/2; |
| 48 | + }else if(t<x) |
| 49 | + { |
| 50 | + s=(s+e)/2; |
| 51 | + } |
| 52 | + else |
| 53 | + { |
| 54 | + return t; |
| 55 | + } |
| 56 | + } |
| 57 | + return closeX(num[s],num[e],x); |
| 58 | + } |
| 59 | + |
| 60 | + public int closeX(int a,int b,int x) |
| 61 | + { |
| 62 | + return Math.abs(a-x)>Math.abs(b-x)?b:a; |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | +第二种解法,在有序数组中求和最接近k的两个数是一个线性时间,算法的时间复杂度是`O(n)`,就是一个双向遍历过程。(**在数组中查找符合某一条件的元素,首先应该想到双向、二分等**)。 |
| 67 | + |
| 68 | +代码如下: |
| 69 | + |
| 70 | + //{java} |
| 71 | + public class Solution { |
| 72 | + public int threeSumClosest(int[] num, int target) { |
| 73 | + Arrays.sort(num); |
| 74 | + int numl=num.length; |
| 75 | + int close = target-99999; |
| 76 | + for(int i=0;i<numl-2;i++) |
| 77 | + { |
| 78 | + int be=i+1, end=numl-1; |
| 79 | + int ta=target-num[i]; |
| 80 | + while(be<end) |
| 81 | + { |
| 82 | + if(num[be]+num[end]>ta) |
| 83 | + { |
| 84 | + end--; |
| 85 | + }else if(num[be]+num[end]<ta) |
| 86 | + { |
| 87 | + be++; |
| 88 | + } |
| 89 | + else |
| 90 | + { |
| 91 | + return target; |
| 92 | + } |
| 93 | + close=closeX(num[i]+num[be+1]+num[be],close,target); |
| 94 | + } |
| 95 | + } |
| 96 | + return close; |
| 97 | + } |
| 98 | + |
| 99 | + public int closeX(int a,int b,int x) |
| 100 | + { |
| 101 | + return Math.abs(a-x)>Math.abs(b-x)?b:a; |
| 102 | + } |
| 103 | + } |
0 commit comments