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 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:
- The value k is positive and will always be smaller than the length of the sorted array.
- Length of the given array is positive and will not exceed 104
- 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.
- If the target
xis less or equal than the first element in the sorted array, the firstkelements are the result. - Similarly, if the target
xis more or equal than the last element in the sorted array, the lastkelements are the result. - Otherwise, we can use binary search to find the
indexof the element, which is equal (when this list hasx) or a little bit larger thanx(when this list does not have it). Then setlowto its leftk-1position, andhighto the rightk-1position of thisindexas 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
lowreaches the lowest index0or thelowelement is closer toxthan thehighelement, decrease thehighindex. - If
highreaches to the highest indexarr.size()-1or it is nearer toxthan thelowelement, increase thelowindex. - The looping ends when there are exactly k elements in [low, high], the subList of which is the result.
- If
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的更多相关文章
- [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 ...
- [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 ...
- 【LeetCode】658. Find K Closest Elements 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/find-k-c ...
- [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 ...
- [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 ...
- 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 ...
- 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 ...
- [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 ...
- [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 ...
随机推荐
- MySQL-怎样使update操作sleep一段时间
)) a on mytest.id=a.id set mytest.name='xiaowang';
- MVC入门——增
创建数据库表如下: 生成EF模型 //------------------------------------------------------------------------------ // ...
- 同一世界服务器架构--Erlang游戏服务器
Erlang最大的优点是方便,很多基础功能都已经集成到Erlang语言中.之前用C++写服务器的时候,管理TCP连接很繁琐,需要写一大堆代码来实现.底层的框架需要写很多代码实现,这样既浪费时间 ...
- 九度OJ 1132:与7无关的数 (数字特性)
时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:1619 解决:1037 题目描述: 一个正整数,如果它能被7整除,或者它的十进制表示法中某个位数上的数字为7, 则称其为与7相关的数.现求所 ...
- virtualbox Units specified don't exist. SHSUCDX can't install.
version infomatin: virtual box: 5.1.12 platform: win10 x64 target OS: win7 x64 问题 在win10系统上,使用virtua ...
- 锁定xcode api 文档
1, 打开终端2, 前往Xcode.app, 命令: cd /Applications/Xcode.app 3, 把头文件修改为只读, 命令: sudo chown -hR root:wheel Co ...
- php遍历统计文件目录和文件
function total($dirname, &$dirnum, &$filenum){ $dir=opendir($dirname); readdir($dir)."& ...
- Ubuntu下声卡驱动解决方法alsa
一.首先介绍一下什么是ALSA : Advanced Linux Sound Architecture 的简称为 ALSA ,译成中文的意思是先进的Linux声音架构(这是google翻译的):一谈到 ...
- 最简单ajax,$.post()用法
最简单的ajax,$.post()用法 $.post("action.php",{'email':$('#email').val(),'address':$('#address') ...
- 电脑设备对于IT人员,犹如武器对于士兵
本人做了多年Softwarer,写些感受. 比我们早的老一代程序员更是用自己的健康总结了一些经验. 先说关于健康方面: 程序员要长期坐着,这对健康损害很大,颈椎腰椎,心肺能力都会衰减.以前只是听说,自 ...