最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

LeetCode 658. Find K Closest Elements

2023-04-21 15:49 作者:您是打尖兒還是住店呢  | 我要投稿

Given a?sorted?integer array?arr, two integers?k?and?x, return the?k?closest integers to?x?in the array. The result should also be sorted in ascending order.

An integer?a?is closer to?x?than an integer?b?if:

  • |a - x| < |b - x|, or

  • |a - x| == |b - x|?and?a < b

?

Example 1:

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

Output: [1,2,3,4]

Example 2:

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

Output: [1,2,3,4]

?

Constraints:

  • 1 <= k <= arr.length

  • 1 <= arr.length <= 104

  • arr?is sorted in?ascending?order.

  • -104?<= arr[i], x <= 104

我是先把跟x的差值的絕對值放到二維數(shù)組中,然后對應(yīng)的值放到另一個位置上,依次排序,

然后找出最接近的k個數(shù)值即可,然后把數(shù)字放到list中就行,其實多操作了一次,沒必要再放到k長度的數(shù)組中,直接放到list中即可。

下面是代碼:

Runtime:?25 ms, faster than?23.48%?of?Java?online submissions for?Find K Closest Elements.

Memory Usage:?43.7 MB, less than?98.88%?of?Java?online submissions for?Find K Closest Elements.


LeetCode 658. Find K Closest Elements的評論 (共 條)

分享到微博請遵守國家法律
洞口县| 阿克| 江陵县| 南安市| 浠水县| 改则县| 遵义市| 宜城市| 慈利县| 伊通| 纳雍县| 电白县| 莱芜市| 当涂县| 长岛县| 舟山市| 灵丘县| 白水县| 宁阳县| 左云县| 泰和县| 东至县| 深水埗区| 伊春市| 永仁县| 克山县| 剑河县| 汪清县| 巧家县| 清水河县| 临城县| 兴国县| 仁布县| 鄂尔多斯市| 广南县| 哈巴河县| 永善县| 石屏县| 阳曲县| 桐乡市| 汝南县|