Binary Search:658. Find K Closest Elements
来源:互联网 发布:月薪8000能招到java 编辑:程序博客网 时间:2024/06/05 03:28
这道题给我们了一个数组,还有两个变量k和x。让我们找数组中离x最近的k个元素,而且说明了数组是有序的,如果两个数字距离x相等的话,取较小的那个。
第一个方法是,设两个指针,一个指向头,一个指向尾,把与x相差大的那个删掉,如果头尾与x相差一样大,右边的删掉。
class Solution {public: vector<int> findClosestElements(vector<int>& arr, int k, int x) { vector<int> res = arr; while(res.size() > k) { int left = 0, right = res.size()-1; if(x - res[left] <= res[right] - x) res.pop_back(); else res.erase(res.begin()); } return res; }};
阅读全文
0 0
- Binary Search:658. Find K Closest Elements
- 658. Find K Closest Elements
- 658. Find K Closest Elements
- 658. Find K Closest Elements
- Find K Closest Elements
- leetcode 658. Find K Closest Elements
- Leetcode 658. Find K Closest Elements
- [LeetCode] 658. Find K Closest Elements
- 658. Find K Closest Elements(快排+折半查找)
- Add to List 658. Find K Closest Elements
- LeetCode:658. Find K Closest Elements程序分析
- leetcode 658. Find K Closest Elements 双指针
- Leetcode 658 Find K Closest Elements
- leetcode_658. Find K Closest Elements ? 待解决
- Find K Closest Elements问题及解法
- Find k closest elements to a given value
- Closest Binary Search Tree Value
- Closest Binary Search Tree Value
- java线程的终止与中断
- Redis 入门介绍
- Spring配置文件<context:property-placeholder>标签使用
- BZOJ 2079 [Poi2010]Guilds 巧解
- nltk练习题
- Binary Search:658. Find K Closest Elements
- 2017.10.22 诸神眷顾的幻想乡 失败总结
- Java开发——反射机制
- 数组或列表切分
- HashCode()方法
- 序列化以及反序列化
- Android studio自动生成布局代码
- 一些比较好的论文集合链接
- DialogFragment实现DatePicker