1. 程式人生 > >leetcode 658. Find K Closest Elements 尋找絕對距離最近K個元素+ 雙指標遍歷

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 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; } };