码迷,mamicode.com
首页 > 其他好文 > 详细

K Closest In Sorted Array - Medium

时间:2018-12-16 15:20:39      阅读:149      评论:0      收藏:0      [点我收藏+]

标签: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

  • 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;
  }
}

 

K Closest In Sorted Array - Medium

标签:for   examples   blog   elements   nts   turn   span   space   return   

原文地址:https://www.cnblogs.com/fatttcat/p/10126564.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!