658. Find K Closest Elements

Posted dysjtu1995

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了658. Find K Closest Elements相关的知识,希望对你有一定的参考价值。

Problem:

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 (10^4)
    Absolute value of elements in the array and x will not exceed (10^4)

思路

Solution (C++):

struct Comp {
    bool operator()(int a, int b) {
        if (abs(a) != abs(b))  return abs(a) > abs(b);
        return a > b;
    }
};
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
    for (int i = 0; i < arr.size(); ++i)  arr[i] -= x;
    priority_queue<int, vector<int>, Comp> que;
    vector<int> res;
    for (auto n : arr)  que.emplace(n);
    while (k-- && !que.empty()) {
        res.push_back(que.top() + x);
        que.pop();
    }
    sort(res.begin(), res.end());
    return res;
}

性能

Runtime: 388 ms??Memory Usage: 14 MB

思路

Solution (C++):


性能

Runtime: ms??Memory Usage: MB


以上是关于658. Find K Closest Elements的主要内容,如果未能解决你的问题,请参考以下文章

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

(双指针二分Binary Search) leetcode 658. Find K closest Elements