标签:
Given a target number, a non-negative integer k
and an integer array A sorted in ascending order, find the k closest numbers to target in A, sorted in ascending order by the difference between the number and target. Otherwise, sorted in ascending order by number if the difference is same.
Example
Given A = [1, 2, 3]
, target = 2
and k = 3
, return [2, 1, 3]
.
Given A = [1, 4, 6, 8]
, target = 3
and k = 3
, return [4, 1, 6]
.
找到第一个大于等于target的index,在index附近查找符合条件的index。
不要将target +- 这样很麻烦。
1 public class Solution { 2 /** 3 * @param A an integer array 4 * @param target an integer 5 * @param k a non-negative integer 6 * @return an integer array 7 */ 8 public int[] kClosestNumbers(int[] A, int target, int k) { 9 if (A == null || A.length == 0) { 10 return A; 11 } 12 if (k > A.length) { 13 return A; 14 } 15 16 int[] result = new int[k]; 17 int index = findIndex(A, target); 18 int begin = index - 1, end = index; 19 for (int i = 0; i < k; i++) { 20 if (begin < 0) { 21 result[i] = A[end++]; 22 } else if (end >= A.length) { 23 result[i] = A[begin--]; 24 } else { 25 if (Math.abs(target - A[begin]) <= Math.abs(A[end] - target)) { 26 result[i] = A[begin--]; 27 } else { 28 result[i] = A[end++]; 29 } 30 } 31 } 32 return result; 33 } 34 35 //find first position which ge target if connot find return A.length - 1 36 private int findIndex(int[] A, int target) { 37 int left = 0, right = A.length - 1; 38 while (left + 1 < right) { 39 int mid = left + (right - left) / 2; 40 if (A[mid] == target) { 41 right = mid; 42 } else if (A[mid] < target) { 43 left = mid; 44 } else { 45 right = mid; 46 } 47 } 48 if (A[left] >= target) { 49 return left; 50 } 51 if (A[right] >= target) { 52 return right; 53 } 54 return A.length - 1; 55 } 56 }
K Closest Numbers In Sorted Array
标签:
原文地址:http://www.cnblogs.com/FLAGyuri/p/5722572.html