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 ...
随机推荐
- Mac OS command line TestNG - “Cannot find class in classpath” error
直接eclipse执行.xml文件可以正确执行 在mac下执行却总报错: [TestNG] [Error] Cannot find class in classpath 最后解决办法,classpat ...
- git 安装及命令
一.window下的git安装 1.安装教程 网上教程一堆.我參考的是这个:Git_Windows 系统下Git安装图解 还有这个也不错 2.环境搭建: 在配置完毕后,自己主动载入到系统环境变量中.如 ...
- SAM4E单片机之旅——11、UART之PDC收发
使用PDC进行数据的收发能减少CPU的开销.这次就使用PDC进行UART数据的接收与发送,同时,也利用TC也实现了PDC的接收超时. PDC是针对外设的DMA控制器.对比DMA控制器,它更为简便,与相 ...
- 【LeetCode】Insertion Sort List
Sort a linked list using insertion sort. //用到O(N)的额外空间 public class Solution { public ListNode inser ...
- PAT 天梯赛 L3-010. 是否完全二叉搜索树 【Tree】
题目链接 https://www.patest.cn/contests/gplt/L3-010 思路 因为是 完全二叉搜索树 可以用 数据 建树的方式 然后 遍历一遍这个 数字 就是 层序遍历 遍历的 ...
- 'gbk' codec can't encode character '\xa5' in position 4546: illegal multibyte sequence错误解决
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='gb18030') 原文 http://blog.csdn.net/jim7424 ...
- windows下的host文件在哪里,有什么作用?
在Window系统中有个Hosts文件(没有后缀名),在Windows98系统下该文件在Windows目录,在Windows2000/XP系统中位于C:\Winnt\System32\Drivers\ ...
- codeforces 702B B. Powers of Two(水题)
题目链接: B. Powers of Two time limit per test 3 seconds memory limit per test 256 megabytes input stand ...
- Chapter2——如何分析Android程序
前几天买了<Android软件安全与逆向分析>这本书,决定在这里记一些笔记. 第一章介绍了如何搭建环境,此处略去:第二章开始讲分析Android程序. 下面按顺序记录关键内容. ----- ...
- ORA-12547: TNS:lost contact
碰到这个ORA-12547: TNS:lost contact的问题,翻了很多资料和METALINK,总结了一下原因: 1 是由于rpm包没有安装,对于我们的生产环境,此包是安装的. admin@p1 ...