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

UPDATE (2017/9/19):
The arr parameter had been changed to an array of integers (instead of a list of integers). Please reload the code definition to get the latest changes.

Approach #1:

class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int len = arr.size();
//cout << x << " " << k << endl;
if (x <= arr[0]) return vector<int> (arr.begin(), arr.begin()+k);
else if (x >= arr[len-1]) return vector<int> (arr.end()-k, arr.end());
else {
int index = lower_bound(arr.begin(), arr.end(), x) - arr.begin();
int low = max(0, index - k - 1), high = min(len-1, index+k-1);
while (high - low > k - 1) {
if (low < 0 || (x - arr[low]) <= (arr[high] - x)) high--;
else if (high > len-1 || (x - arr[low]) > (arr[high] - x)) low++;
}
return vector<int> (arr.begin()+low, arr.begin()+high+1);
}
}
};

Runtime: 72 ms, faster than 98.40% of C++ online submissions for Find K Closest Elements.

Analysis:

The original array has been sorted so we can take this advantage by the following steps.

  1. If the target x is less or equal than the first element in the sorted array, the first k elements are the result.
  2. Similarly, if the target x is more or equal than the last element in the sorted array, the last k elements are the result.
  3. Otherwise, we can use binary search to find the index of the element, which is equal (when this list has x) or a little bit larger than x(when this list does not have it). Then set low to its left k-1 position, and high to the right k-1 position of this index as a start. The desired k numbers must in this rang [index-k-1, index+k-1]. So we can shrink this range to get the result using the following rules.
    • If low reaches the lowest index 0 or the low element is closer to x than the high element, decrease the high index.
    • If high reaches to the highest index arr.size()-1 or it is nearer to x than the low element, increase the low index.
    • The looping ends when there are exactly k elements in [low, high], the subList of which is the result.

Complexity Analysis

  • Time complexity : O(log(n)+k)O(log(n)+k). O(log(n))O(log(n)) is for the time of binary search, while O(k)O(k) is for shrinking the index range to k elements.

  • Space complexity : O(k)O(k). It is to generate the required sublist.

658. Find K Closest Elements的更多相关文章

  1. [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 resul ...

  2. [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 resul ...

  3. 【LeetCode】658. Find K Closest Elements 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/find-k-c ...

  4. [LeetCode] 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 resul ...

  5. [Swift]LeetCode658. 找到 K 个最接近的元素 | Find K Closest Elements

    Given a sorted array, two integers k and x, find the kclosest elements to x in the array. The result ...

  6. Find K Closest Elements

    Given a sorted array, two integers k and x, find the k closest elements to x in the array. The resul ...

  7. LeetCode - Find K Closest Elements

    Given a sorted array, two integers k and x, find the k closest elements to x in the array. The resul ...

  8. [leetcode-658-Find K Closest Elements]

    Given a sorted array, two integers k and x, find the k closest elements to x in the array. The resul ...

  9. [LeetCode] Top K Frequent Elements 前K个高频元素

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

随机推荐

  1. 数据仓库建模与ETL的实践技巧(转载)

    一.Data仓库的架构 Data仓库(Data Warehouse DW)是为了便于多维分析和多角度展现而将Data按特定的模式进行存储所建立起来的关系型Datcbase,它的Data基于OLTP源S ...

  2. 模式识别之分类器knn---c语言实现带训练数据---反余弦匹配

    邻近算法   KNN算法的决策过程 k-Nearest Neighbor algorithm是K最邻近结点算法(k-Nearest Neighbor algorithm)的缩写形式,是电子信息分类器算 ...

  3. CSDN第一期总结之三:Thread的问题(转)

    C#是一门支持多线程的语言,因此线程的使用也是比较常见的.由于线程的知识在Win32编程的时候已经说得过多,所以在.Net中很少介绍这部分(可能.Net不觉得这部分是它所特有的). 那么线程相关的问题 ...

  4. python的self

    python类定义里面的self就是指的该类的对象本身.

  5. Hadoop实战-使用Eclipse开发Hadoop API程序(四)

    一.准备运行所需Jar包 1)avro-1.7.4.jar 2)commons-cli-1.2.jar 3)commons-codec-1.4.jar 4)commons-collections-3. ...

  6. windows server安装oracle

    倒腾windows server的时候一定要先整net framework然后再安装oracle不然连不上或者装一下client 也能连上但是为了不安装client一定要先装framework!

  7. apache下实现301永久性重定向的方法

    因为博客是使用了www.php100.com作为博客域名,所以想实现php100.com全部重定向(跳转)到www.php100.com.同时按照google的建议,使用服务器端 301 重定向,为了 ...

  8. vim实现代码缩进和可视区域的字符串替换

    今天2014年9月12号,实现了vim下的代码自动缩进和替换可视区域的字符串,之前一直在用vim这个强大的编辑器,它的强大只有用了的人才知道,现在把这两个很强大的功能展示出来,有个这两个功能,即使你写 ...

  9. CSS阶段总结

    CSS布局之左右布局与左中右布局 方法:为子元素设置浮动,然后在其父元素上使用clearfix类来清除浮动.代码示例: html部分: <div class="parent clear ...

  10. [RK3288][Android6.0] 调试笔记 --- eMMC分区号和名字的对应【转】

    本文转载自:http://blog.csdn.net/kris_fei/article/details/77318410 Platform: Rockchip OS: Android 6.0 Kern ...