HDU 2115 I Love This Game(结构体排序 or pair)
999
2022-08-23
[leetcode] 658. Find K Closest Elements
Description
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=3Output: [1,2,3,4]
Example 2:
Input: [1,2,3,4,5], k=4, x=-1Output: [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 104Absolute value of elements in the array and x will not exceed 104
分析
题目的意思是:给一个数组,k,x,然后在数组中找出与x最近的k个值。
每次比较的是mid位置和x的距离跟mid+k跟x的距离,以这两者的大小关系来确定二分法折半的方向,最后找到最近距离子数组的起始位置.
代码
class Solution {public: vector
参考文献
[LeetCode] Find K Closest Elements 寻找K个最近元素
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~