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
- A is not null
- K is guranteed to be >= 0 and K is guranteed to be <= A.length
Return
- A size K integer array containing the K closest numbers(not indices) in A, sorted in ascending order by the difference between the number and T.
Examples
- A = {1, 2, 3}, T = 2, K = 3, return {2, 1, 3} or {2, 3, 1}
- A = {1, 4, 6, 8}, T = 3, K = 3, return {4, 1, 6}
和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; } }
原文地址:https://www.cnblogs.com/fatttcat/p/10126564.html
时间: 2024-10-09 01:26:26