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. vi 之行号操作---显示行号、跳到指定行

    1.设置行号显示 esc ->:->set nu 2.跳到指定行 esc-> 123gg 3. 进入命令模式 ?一:在冒号下输入 vim vi 在命令模式中 使用 d(版本不同 使用 ...

  2. 2016/07/07 mymps(蚂蚁分类信息/地方门户系统)

    mymps(蚂蚁分类信息/地方门户系统)是一款基于php mysql的建站系统.为在各种服务器上架设分类信息以及地方门户网站提供完美的解决方案. mymps,整站生成静态,拥有世界一流的用户体验,卓越 ...

  3. python的self

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

  4. 正则表达式测试工具之Regex Match Tracer

    下载地址:http://www.regex-match-tracer.com/downloads 使用示例1:匹配 使用示例2:替换

  5. windows搭建FTP服务器实战

    第一步:创建用户名密码(ftp使用) 1.1.点击“开始”菜单,选择“控制面板”. 1.2.选择“管理工具”—>“计算机管理” 1.3. 选择“本地用户和组”下的用户,右键选择“新用户” 输入用 ...

  6. 阻止SSIS import excel时的默认行为

    为什么SSIS总是错误地获取Excel数据类型,以及如何解决它! 由Concentra发布 2013年5月15日 分享此页面 分享   发现Concentra的分析解决方案 Concentra的分析和 ...

  7. 04-树4 是否同一棵二叉搜索树(25 point(s)) 【Tree】

    04-树4 是否同一棵二叉搜索树(25 point(s)) 给定一个插入序列就可以唯一确定一棵二叉搜索树.然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到.例如分别按照序列{2, 1, 3}和 ...

  8. Gym - 100676F Palindrome —— 并查集

    题目链接:https://vjudge.net/contest/155789#problem/E 题解: 由于是回文串,所以可以先将在对称位置的字符放在同一个集合(如果期间有两个非‘?’,且不相等,则 ...

  9. iOS-个人开发者账号转公司开发者账号(邓白氏码申请教程)

    邓白氏编码申请 个人开发者账号转公司开发者账号,首先要申请邓白氏编码-DUNS,打开https://developer.apple.com/support/进行DUNS申请! 步骤如下: 1.选择Me ...

  10. hdu-4857 逃生(拓扑序)

    题目链接: 逃生 Time Limit: 2000/1000 MS (Java/Others)     Memory Limit: 32768/32768 K (Java/Others) Proble ...