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 ...
随机推荐
- vi 之行号操作---显示行号、跳到指定行
1.设置行号显示 esc ->:->set nu 2.跳到指定行 esc-> 123gg 3. 进入命令模式 ?一:在冒号下输入 vim vi 在命令模式中 使用 d(版本不同 使用 ...
- 2016/07/07 mymps(蚂蚁分类信息/地方门户系统)
mymps(蚂蚁分类信息/地方门户系统)是一款基于php mysql的建站系统.为在各种服务器上架设分类信息以及地方门户网站提供完美的解决方案. mymps,整站生成静态,拥有世界一流的用户体验,卓越 ...
- python的self
python类定义里面的self就是指的该类的对象本身.
- 正则表达式测试工具之Regex Match Tracer
下载地址:http://www.regex-match-tracer.com/downloads 使用示例1:匹配 使用示例2:替换
- windows搭建FTP服务器实战
第一步:创建用户名密码(ftp使用) 1.1.点击“开始”菜单,选择“控制面板”. 1.2.选择“管理工具”—>“计算机管理” 1.3. 选择“本地用户和组”下的用户,右键选择“新用户” 输入用 ...
- 阻止SSIS import excel时的默认行为
为什么SSIS总是错误地获取Excel数据类型,以及如何解决它! 由Concentra发布 2013年5月15日 分享此页面 分享 发现Concentra的分析解决方案 Concentra的分析和 ...
- 04-树4 是否同一棵二叉搜索树(25 point(s)) 【Tree】
04-树4 是否同一棵二叉搜索树(25 point(s)) 给定一个插入序列就可以唯一确定一棵二叉搜索树.然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到.例如分别按照序列{2, 1, 3}和 ...
- Gym - 100676F Palindrome —— 并查集
题目链接:https://vjudge.net/contest/155789#problem/E 题解: 由于是回文串,所以可以先将在对称位置的字符放在同一个集合(如果期间有两个非‘?’,且不相等,则 ...
- iOS-个人开发者账号转公司开发者账号(邓白氏码申请教程)
邓白氏编码申请 个人开发者账号转公司开发者账号,首先要申请邓白氏编码-DUNS,打开https://developer.apple.com/support/进行DUNS申请! 步骤如下: 1.选择Me ...
- hdu-4857 逃生(拓扑序)
题目链接: 逃生 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Proble ...