1. 程式人生 > >[leetcode]658. Find K Closest Elements絕對距離最近的K個元素

[leetcode]658. Find K Closest Elements絕對距離最近的K個元素

Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.

Example 1:

Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]

 

Example 2:

Input: [1,2,3,4,5], k=4, x=-1
Output: [1,2,3,4]

 

Note:

  1. The value k is positive and will always be smaller than the length of the sorted array.
  2. Length of the given array is positive and will not exceed 104
  3. Absolute value of elements in the array and x will not exceed 104

 

題目

 

思路

本題要求我們在sorted array中找出K個最相近於x的數。因為輸出結果一定排好序的、k-size的區間,若能找出該區間的leftBound,向右邊走k個值,就可以得到desired output。

即問題轉化為,怎樣找到該leftBound呢? 在[0, n-k]中使用binary search查詢

 

 

 

 

程式碼

 1 class Solution {
 2   public List<Integer> findClosestElements(int
[] arr, int k, int x) { 3 int begin = 0; 4 int end = arr.length - k; 5 while(begin < end){ 6 int mid = begin + (end - begin) /2 ; 7 if(x > arr[mid]){ 8 if( x - arr[mid] > arr[mid + k] - x){ 9 begin = mid +1; 10 }else{ 11 end = mid; 12 } 13 }else{ 14 end = mid; 15 } 16 } 17 int index = begin; 18 List<Integer> result = new ArrayList<>() ; 19 while( k != 0){ 20 result.add(arr[index++]); 21 k--; 22 } 23 return result; 24 } 25 }