标签:for examples blog elements nts turn span space return
Given a target integer T, a non-negative integer K and an integer array A sorted in ascending order, find the K closest numbers to T in A.
Assumptions
Return
Examples
和leetcode 658. Find K Closest Elements https://www.cnblogs.com/fatttcat/p/10062228.html
不同的地方是,本题要求输出的array是按与target的距离排序
time: O(log(n) + k), space: O(1)
public class Solution { public int[] kClosest(int[] array, int target, int k) { // Write your solution here int left = 0, right = array.length - 1; while(left + 1 < right) { int mid = left + (right- left) / 2; if(array[mid] >= target) right = mid; else left = mid; } int tmp; if(array[right] <= target) tmp = right; if(array[left] <= target) tmp = left; else tmp = -1; left = tmp; right = left + 1; int[] res = new int[k]; for(int i = 0; i < k; i++) { if(left >= 0 && right <= array.length - 1 && Math.abs(array[left] - target) <= Math.abs(array[right] - target)) res[i] = array[left--]; else if(left >= 0 && right > array.length - 1) res[i] = array[left--]; else res[i] = array[right++]; } return res; } }
K Closest In Sorted Array - Medium
标签:for examples blog elements nts turn span space return
原文地址:https://www.cnblogs.com/fatttcat/p/10126564.html