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. stretchableImageWithLeftCapWidth

    本文转载至 http://www.cnblogs.com/bandy/archive/2012/04/25/2469369.html (NSInteger)topCapHeight 这个函数是UIIm ...

  2. IOS8 通知中心(Notification Center)新特性

     本文转载至 http://blog.csdn.net/jinkaiouyang/article/details/30029441   ios手机apple通知中心notificationCenter ...

  3. EasyDarwin开源流媒体音视频云平台遇到的奇葩问题:内网运行正常,公网流媒体不通

    最近在帮助EasyDarwin的用户部署EasyNVR+EasyDarwin云平台+EasyClient方案的过程中,遇到一个问题,EasyNVR分布在用户各地区现场的内网中,EasyDarwin云平 ...

  4. Spring MVC的映射请求

    一.SpringMVC常用注解 @Controller 声明Action组件 @Service    声明Service组件    @Service("myMovieLister" ...

  5. Hibernate中的HQL语言

    一.HQL语言简介 HQL全称是Hibernate Query Language,它提供了是十分强大的功能,它是针对持久化对象,直接取得对象,而不进行update,delete和insert等操作.而 ...

  6. This means that only a small number of nodes must be read from disk to retrieve an item.

    http://cis.stvincent.edu/html/tutorials/swd/btree/btree.html Introduction A B-tree is a specialized ...

  7. Hadoop集群搭建-Hadoop2.8.0安装(三)

    一.准备安装介质 a).hadoop-2.8.0.tar b).jdk-7u71-linux-x64.tar 二.节点部署图 三.安装步骤 环境介绍: 主服务器ip:192.168.80.128(ma ...

  8. codeforces 570D.Tree Requests

    [题目大意]: 给定一棵树,树的每个节点对应一个小写字母字符,有m个询问,每次询问以vi为根节点的子树中,深度为hi的所有节点对应的字符能否组成一个回文串: [题目分析]: 先画个图,可看出每次询问的 ...

  9. 侧方位停车想一次过,掌握边线30cm很重要!

    侧方位停车要想一次过关,关键在于保持车身距离库边线30cm左右的距离.但是,往往有很多学员掌控不好这个距离,导致倒库时压线.那么,如何找准这个30cm呢?下面,小编就来教大家方法,赶紧学习吧! 侧方位 ...

  10. Program received signal SIGSEGV, Segmentation fault.

    GDB调试的时候出现了: Program received signal SIGSEGV, Segmentation fault.(程序收到信号SIGSEGV,分段故障) SIGSEGV:在POSIX ...