[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 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
这道题给我们了一个数组,还有两个变量k和x。让找数组中离x最近的k个元素,而且说明了数组是有序的,如果两个数字距离x相等的话,取较小的那个。从给定的例子可以分析出x不一定是数组中的数字,由于数组是有序的,所以最后返回的k个元素也一定是有序的,那么其实就是返回了原数组的一个长度为k的子数组,转化一下,实际上相当于在长度为n的数组中去掉 n-k 个数字,而且去掉的顺序肯定是从两头开始去,因为距离x最远的数字肯定在首尾出现。那么问题就变的明朗了,每次比较首尾两个数字跟x的距离,将距离大的那个数字删除,直到剩余的数组长度为k为止,参见代码如下:
解法一:
- class Solution {
- public:
- vector<int> findClosestElements(vector<int>& arr, int k, int x) {
- vector<int> res = arr;
- while (res.size() > k) {
- if (x - res.front() <= res.back() - x) {
- res.pop_back();
- } else {
- res.erase(res.begin());
- }
- }
- return res;
- }
- };
下面这种解法是论坛上的高分解法,用到了二分搜索法。其实博主最开始用的方法并不是帖子中的这两个方法,虽然也是用的二分搜索法,但博主搜的是第一个不小于x的数,然后同时向左右两个方向遍历,每次取和x距离最小的数加入结果 res 中,直到取满k个为止。但是下面这种方法更加巧妙一些,二分法的判定条件做了一些改变,就可以直接找到要返回的k的数字的子数组的起始位置,感觉非常的神奇。每次比较的是 mid 位置和x的距离跟 mid+k 跟x的距离,以这两者的大小关系来确定二分法折半的方向,最后找到最近距离子数组的起始位置,参见代码如下:
解法二:
- class Solution {
- public:
- vector<int> findClosestElements(vector<int>& arr, int k, int x) {
- int left = , right = arr.size() - k;
- while (left < right) {
- int mid = left + (right - left) / ;
- if (x - arr[mid] > arr[mid + k] - x) left = mid + ;
- else right = mid;
- }
- return vector<int>(arr.begin() + left, arr.begin() + left + k);
- }
- };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/658
类似题目:
Guess Number Higher or Lower II
Find K-th Smallest Pair Distance
参考资料:
LeetCode All in One 题目讲解汇总(持续更新中...)
[LeetCode] 658. Find K Closest Elements 寻找K个最近元素的更多相关文章
- [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 ...
- 【LeetCode】658. Find K Closest Elements 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/find-k-c ...
- [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 - 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 ...
- 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 ...
- [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-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 ...
- Top K Frequent Elements 前K个高频元素
Top K Frequent Elements 347. Top K Frequent Elements [LeetCode] Top K Frequent Elements 前K个高频元素
随机推荐
- @Valid 数据校验 + 自定义全局异常信息
关于javax.validation.Validator校验的使用 对于要校验的实体类:其需要校验的字段上需要添加注解 实际例子 使用:首先要拿到 validator的子类 Validator val ...
- putty连接centos慢
用的vmware下的centos minimal镜像,开发时,用putty连接很慢,一分多钟, 解决方案: 禁用GSSAPI认证有两个方式:客户端和服务端 直接配置你ssh客户端的文件/etc/ssh ...
- js删除html标记 去掉所有html标记
js删除html标记 去掉所有html标记 function delHtml(str){ return str.replace(/<[^>]+>/g,""); / ...
- pid相关命令
pidof 查找正在运行进程的进程号(pid)的工具 pidof - find the process ID of a running program 参数: -s 表示只返回1个 pid -x 表示 ...
- spring boot的gradle整合日志
1.引入包configurations { providedRuntime // remove default logger all*.exclude group: 'org.springframew ...
- python 自带模块 os模块
os模块 首先可以打开cmd输入python进入交互界面 然后输入 dir(os) 就可以看到os的全部用法了 我们简单的举几个例子就行了. 写入os.getcwd() 可以查看当前所在路径 i ...
- vue 开发系列(九) VUE 动态组件的应用
业务场景 我们在开发表单的过程中会遇到这样的问题,我们选择一个控件进行配置,控件有很多中类型,比如文本框,下来框等,这些配置都不同,因此需要不同的配置组件来实现. 较常规的方法是使用v-if 来实现, ...
- Python必备面试题
Python部分 1. __new__.__init__区别,如何实现单例模式,有什么优点 __new__是一个静态方法,__init__是一个实例方法 __new__返回一个创建的实例,__in ...
- React 受控组件和非受控组件
需求用户名自动获取 onChange用户状态发生改变 就获取值 就是时时获取值 使用onChange 点击按钮 获取密码 只要绑定了点击事件 就可以获取值 通过 let usercont=event. ...
- Ubuntu下部署Portainer管理docker
在上一篇文章中,我们部署了Shipyard来管理docker集群,总体比较简单,而且Shipyard界面风格很简约,还是比较喜欢的,但是正如提出的node节点无法显示bug,以及该项目早已停止维护,让 ...