本文主要是介绍Find K Closest Elements问题及解法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
问题描述:
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=3 Output: [1,2,3,4]
Input: [1,2,3,4,5], k=4, x=-1 Output: [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;}
};
这篇关于Find K Closest Elements问题及解法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!