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

这道题给我们了一个数组,还有两个变量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

Guess Number Higher or Lower

Find K-th Smallest Pair Distance

参考资料:

https://leetcode.com/problems/find-k-closest-elements/

https://leetcode.com/problems/find-k-closest-elements/discuss/106419/O(log-n)-Java-1-line-O(log(n)-%2B-k)-Ruby

https://leetcode.com/problems/find-k-closest-elements/discuss/202785/Very-simple-Java-O(n)-solution-using-two-pointers

https://leetcode.com/problems/find-k-closest-elements/discuss/106426/JavaC%2B%2BPython-Binary-Search-O(log(N-K)-%2B-K)

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 658. Find K Closest Elements 寻找K个最近元素的更多相关文章

  1. [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 ...

  2. 【LeetCode】658. Find K Closest Elements 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/find-k-c ...

  3. [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 ...

  4. 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 ...

  5. 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 ...

  6. [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 ...

  7. 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. Top K Frequent Elements 前K个高频元素

    Top K Frequent Elements 347. Top K Frequent Elements [LeetCode] Top K Frequent Elements 前K个高频元素

随机推荐

  1. FaaS(函数即服务) + BaaS(后台即服务)

    作者 | 黄子毅(紫益) 阿里前端技术专家 导读:前端开发者是最早享受到 “Serverless” 好处的群体,因为浏览器就是一个开箱即用.甚至无需为计算付费的环境!Serverless 把前端开发体 ...

  2. elementui树表修改子节点不能实时更新的解决办法

    在使用ElementUI提供的树表(el-table)的时候发现,如果手动通过JS修改了某个节点的children中的一条记录(子节点)的话,并不会自动刷新. 简单分析了一下,原因大概是因为VUE的数 ...

  3. OfType<string>()

    object[] vals = { 1, "Hello", true, "World", 9.1 }; IEnumerable<double> ju ...

  4. IIS错误:在唯一密钥属性“fileExtension”设置为“.json”时,无法添加类型为“mimeMap”的重复集合项

    在用visual studio 打开一个asp.net mvc 项目时,ctrl+f5运行,发现页面无法加载图片.js.json文件. 按F12查看错误,发现500错误.打开报错的js文件,提示: I ...

  5. Javaweb常用解决问题连接

    1.javaweb的idea如何创建及配置web项目 https://www.jianshu.com/p/8d49d36a3c7e 2.servlet的建立以及部署 https://blog.csdn ...

  6. linux shell编程,先等10秒再判断是否有进程存在,存在就再等10秒再杀了进程才运行

    linux shell编程,先等10秒再判断是否有进程存在,存在就再等10秒再杀了进程才运行 crontab每分钟执行一次,但5秒以上才有更新数据,有时候一分钟可能跑不完上一个进程,需要先等10秒再判 ...

  7. MES系统如何帮助烟草行业管理生产流程

    与很多其他行业一样,烟草MES系统可以帮助卷烟企业实现智能生产.精益制造.快速实现烟草企业数字化车间的创建,助力企业实现改造升级,从而提升企业生产效率,降低生产成产.烟草行业得MES者得天下. 烟草行 ...

  8. pushad与popad

    版权声明:本文为博主原创文章,转载请附上原文出处链接和本声明.2019-08-24,00:40:12作者By-----溺心与沉浮----博客园 PUSHAD与POPAD 这两条指令其实就是讲EAX,E ...

  9. [转]技术比较Agent和Agentless监控优缺点

    本文并非原创,转自:http://wenku.baidu.com/link?url=NGT2NA7Lf6fZSPmcOxFQqL4cYROHlIOJyiWCnGdwv3kljMqub-6zyjgsSw ...

  10. 基本运算符,流程控制if、while

    基本运算符 算术运算符 运算符 描述 实例 + 加 a + b - 减 a - b * 乘 a * b / 除 a / b % 取余 a % b // 整除 a // b ** 幂运算 a ** b ...