From 806637983a379f9b252d980da8b050cc9763d923 Mon Sep 17 00:00:00 2001 From: Qiming Xu <458173774@qq.com> Date: Wed, 21 Feb 2024 00:30:51 +0000 Subject: [PATCH] leetcode: finished #658 --- content/leetcode/2024/2.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/content/leetcode/2024/2.md b/content/leetcode/2024/2.md index a94db568..a7111e38 100644 --- a/content/leetcode/2024/2.md +++ b/content/leetcode/2024/2.md @@ -3,6 +3,44 @@ title: 2024.2 draft: false --- +# 2024.2.21 + +```python +# +# @lc app=leetcode.cn id=658 lang=python3 +# +# [658] 找到 K 个最接近的元素 +# + +# @lc code=start +from typing import List + + +class Solution: + def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]: + left, right = 0, len(arr) - 1 + while left < right: + mid = left + (right - left) // 2 + if arr[mid] < x: + left = mid + 1 + else: + right = mid + left, right = left - 1, left + while right - left - 1 < k: + if left < 0: + right += 1 + elif right >= len(arr): + left -= 1 + elif x - arr[left] <= arr[right] - x: + left -= 1 + else: + right += 1 + return arr[left + 1 : right] + + +# @lc code=end +``` + # 2024.2.20 ```python