leetcode 658. Find K Closest Elements 双指针
来源:互联网 发布:ubuntu权限不够 编辑:程序博客网 时间:2024/06/16 16:25
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.
本题题意很简单,最直接的方法,就是暴力查找,但是后来发现一个更加方便的方法,很棒的做法。
这道题给我们了一个数组,还有两个变量k和x。让我们找数组中离x最近的k个元素,而且说明了数组是有序的,如果两个数字距离x相等的话,取较小的那个。从给定的例子可以分析出x不一定是数组中的数字,我们想,由于数组是有序的,所以最后返回的k个元素也一定是有序的,那么其实就是返回了原数组的一个长度为k的子数组,转化一下,实际上相当于在长度为n的数组中去掉n-k个数字,而且去掉的顺序肯定是从两头开始去,应为距离x最远的数字肯定在首尾出现。那么问题就变的明朗了,我们每次比较首尾两个数字跟x的距离,将距离大的那个数字删除,直到剩余的数组长度为k为止,
代码如下:
#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <numeric>#include <cmath>#include <regex>using namespace std;class Solution {public: vector<int> findClosestElements(vector<int>& arr, int k, int x) { vector<int> res = arr; while (res.size() > k) { int left = abs(res[0]-x); int right = abs(res.back() - x); if (left > right) res.erase(res.begin()); else res.pop_back(); } return res; }};
- leetcode 658. 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
- 658. Find K Closest Elements
- 658. Find K Closest Elements
- LeetCode:658. Find K Closest Elements程序分析
- Leetcode 658 Find K Closest Elements
- Find K Closest Elements
- Binary Search:658. Find K Closest Elements
- 658. Find K Closest Elements(快排+折半查找)
- Add to List 658. Find K Closest Elements
- leetcode_658. Find K Closest Elements ? 待解决
- Find K Closest Elements问题及解法
- Find k closest elements to a given value
- Find k most repeating elements
- LeetCode|Top K Frequent Elements
- 分布式系统事务一致性的讨论
- Redis、MongoDB及Memcached的区别
- 系统修复
- Syslog在网络管理中的应用
- PHP开启mysqli扩展
- leetcode 658. Find K Closest Elements 双指针
- logback.xml配置解析
- Elasticsearch聚合查询
- Java并发编程:线程池的使用
- Linux
- echarts图表动态获取后台数据详解(三)--ajax跨域请求
- 解引用指针的双重间接
- 禁止微信内置浏览器调整字体大小
- 从零开始学Python【1】--数据类型及结构