Important Node:
1) This problem has two parts:
a. find the closest number's to the target and return its index. This is standard binary search problem. O(logN)
b. find kth closest number. This is two pointers problem. O(k)
in this b part, be careful about the boundary. j should be less than nums.length instead of k, because rstIdx < k already control it.
2) Near to pay attension to coner case when k is equal to 0, just return an empty array instead of null
3) rst[rstIdx++] => rst[rstIdx] then rstIdx++
rst[++rstIdx] => rstIdx++ then rst[rstIdx(the one that already increased)]
public class Solution { /** * @param A an integer array * @param target an integer * @param k a non-negative integer * @return an integer array */ public int[] kClosestNumbers(int[] A, int target, int k) { // Write your code here if (A == null || A.length == 0) { return null; } if (k == 0) { return new int[0]; } //find the nearst number int nearIdx = findNearestIdx(A, target); //find the first Kth closest number int[] rst = findKthNearest(A, k, target, nearIdx); return rst; } private int findNearestIdx(int[] nums, int target) { int start = 0; int end = nums.length - 1; while (start + 1 < end) { int mid = start + (end - start) / 2; if (nums[mid] == target) { return mid; } else if (nums[mid] < target) { start = mid; } else { end = mid; } } int startDis = Math.abs(nums[start] - target); int endDis = Math.abs(nums[end] - target); return startDis <= endDis ? start : end; } private int[] findKthNearest(int[] nums, int k, int target, int nearIdx) { int[] rst = new int[k]; rst[0] = nums[nearIdx]; int rstIdx = 1; int i = nearIdx - 1, j = nearIdx + 1; while (rstIdx < k && i >=0 && j < nums.length) { int disi = Math.abs(target - nums[i]); int disj = Math.abs(target - nums[j]); if (disi <= disj) { rst[rstIdx++] = nums[i--]; } else { rst[rstIdx++] = nums[j++]; } } while (rstIdx < k && i >= 0) { rst[rstIdx++] = nums[i--]; } while (rstIdx < k && j < nums.length) { rst[rstIdx++] = nums[j++]; } return rst; } }
Method Two:
1) Find the first Index that is larger than target
2) Using two pointers to find Kth number. All the index that is less than the "first Index", use target - nums[i]
Code:
http://www.jiuzhang.com/solutions/k-closest-numbers-in-sorted-array/