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; }};
阅读全文
0 0
- Find K Closest Elements问题及解法
- Find K Closest Elements
- 658. Find K Closest Elements
- 658. Find K Closest Elements
- 658. Find K Closest Elements
- Top K Frequent 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:658. Find K Closest Elements
- leetcode_658. Find K Closest Elements ? 待解决
- Find k closest elements to a given value
- 658. Find K Closest Elements(快排+折半查找)
- Add to List 658. Find K Closest Elements
- LeetCode:658. Find K Closest Elements程序分析
- leetcode 658. Find K Closest Elements 双指针
- 3Sum Closest问题及解法
- Object.assign方法的使用和splice方法用法
- 杂记1123
- A2C Advantage Actor-Critic源码
- 欢迎使用CSDN-markdown编辑器
- Spring MVC工作流程图
- Find K Closest Elements问题及解法
- MFC中使用TeeChart绘制三维曲线
- 一个超级简单的居中
- ANDROID的 BLUETOOTH 实现机制与架构
- 解决 Eclipse出现the user operation is waiting的问题
- 4.4 类与程序的基本结构(略)
- pgAdmin4 设置 中文 界面
- 认真写代码
- mybatis面试题总结大全