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. Appium python自动化测试系列之认识Appium(四)

    ​4.1界面认识 在之前安装appium的时候说过我们有两种方法安装,也就有两种结果,一种是有界面的,一种是没有界面的,首先我们先讲一下有界面的,以及界面有哪些东西. 首先看第一幅图,如果你的是win ...

  2. eclipse的debug使用(转载)

    出处:http://www.blogjava.net/yxhxj2006/archive/2012/08/30/386621.html 远程Debug: http://blog.sina.com.cn ...

  3. 解决火狐访问(localhost)本地网站提示输入用户名密码

    VS在调试程序时浏览器一直提示要输入用户名及密码,但是我程序根本没有登录界面,最后终于找到了解决方案,如下: 1.在火狐浏览器地址栏中输入:about:config 2.然后在搜索文本框中输入:NTL ...

  4. 点击文本选中checkbox

    <checbox文本编辑/>      : 只点击checkbox时,才可以选中,点击文本时无法选中 <label><checbox文本编辑/></label ...

  5. 【C++基础学习】数据封装、构造函数

    第一部分 类和对象 内存中按照用途被划分的五个区:栈区.堆区.全局区.常量区.代码区栈区由系统来进行控制,无论是内存的分配还是回收都不需要程序员关心堆区由new分配内存,使用完成之后必须使用delet ...

  6. Express中的Ejs模板传值问题

    在Ejs模板传值过程中,route下的变量值通过res.sender()中的变量参数传给views, 这时在views中若该变量在javascript代码中使用,可直接使用该变量,不必使用<% ...

  7. 将前端文件和Go程序打包

    我今天项目上碰见个需求,前端小哥给我写了个页面,要搭配我的Go程序一起使用,突然想到Go可以打包静态页面,而且调用也很方便,所以操作了一下,成功,我把它记录下来,作为以后的回顾和复习. 首先,我们需要 ...

  8. javascript 正则表达式 详细入门教程

    1.什么是正则表达式 定义: 一个用来搜索.匹配.处理一些符合特定语法规则的一个强大的字符串处理工具. 用途: 进行特定字符和字符串的搜索 替换字符串中指定的字符或字符串 验证字符串是否符合需求 2. ...

  9. linux 网络设备,网卡配置 ,相关

    网络设备,网卡配置: Eth0是物理网卡:唯一mac地址,Bcast:广播地址,MAsk:子网掩码, Lo:系统自带的回环的ip地址,可以做一些基本的测试应用,比如没有网卡就用127.0.0.1, r ...

  10. CentOS软件管理之源代码以及RPM软件包管理

    在Linux系统下,对于软件包的管理有多种机制,有源代码方式.RPM软件包管理方式以及YUM软件管理方式,本篇随笔将详细讲解CentOS下源代码形式安装软件以及RPM软件包管理机制 一.源代码形式 首 ...