Find K Closest Elements问题及解法

来源:互联网 发布:喀秋莎录屏软件范例 编辑:程序博客网 时间:2024/06/06 16:32

问题描述:

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.

示例:

Input: [1,2,3,4,5], k=4, x=3Output: [1,2,3,4]
Input: [1,2,3,4,5], k=4, x=-1Output: [1,2,3,4]

问题分析:

找到第一个大于等于x的索引位置,从该索引开始分别向左向右共拓展k个元素,这k个元素就是答案。


过程详见代码:

class Solution {public:    vector<int> findClosestElements(vector<int>& arr, int k, int x) {        int index = 0;int mi = INT_MAX;for (int i = 0; i < arr.size(); i++){if (abs(arr[i] - x) < mi){mi = abs(arr[i] - x);index = i;}}vector<int> res;res.push_back(arr[index]);int l = index - 1, r = index + 1;while (--k){if (l >= 0 && r < arr.size()){if (abs(arr[l] - x) > abs(arr[r] - x)){res.push_back(arr[r]);r++;}else{res.push_back(arr[l]);l--;}}else if (l >= 0){res.push_back(arr[l]);l--;}else if (r < arr.size()){res.push_back(arr[r]);r++;}else break;}sort(res.begin(), res.end());return res;    }};