您的位置:首页 > 其它

leetcode 658. Find K Closest Elements 寻找绝对距离最近K个元素+ 双指针遍历

2017-12-21 18:01 447 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: