8000 * Done with "2200. Find All K-Distant Indices in an Array". · garciparedes/leetcode@8aac105 · GitHub
[go: up one dir, main page]

Skip to content

Commit 8aac105

Browse files
committed
* Done with "2200. Find All K-Distant Indices in an Array".
1 parent b5ec657 commit 8aac105

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
from math import ceil
2+
3+
4+
class Solution:
5+
def findKDistantIndices(self, nums: List[int], key: int, k: int) -> List[int]:
6+
key_indexes = list()
7+
for i in range(len(nums)):
8+
if nums[i] == key:
9+
key_indexes.append(i)
10+
11+
ans = list()
12+
for i in range(len(nums)):
13+
if self._is_k_distant(key_indexes, i, k):
14+
ans.append(i)
15+
16+
return ans
17+
18+
@staticmethod
19+
def _is_k_distant(indexes: list[int], i: int, k: int) -> bool:
20+
21+
left, right = 0, len(indexes) - 1
22+
while left < right:
23+
mid = ceil((left + right) / 2)
24+
25+
if indexes[mid] > i:
26+
right = mid - 1
27+
else:
28+
left = mid
29+
30+
if abs(indexes[left] - i) <= k:
31+
return True
32+
33+
if left < len(indexes) - 1:
34+
left += 1
35+
return abs(indexes[left] - i) <= k
36+
37+
return False
38+
39+
40+
41+

0 commit comments

Comments
 (0)
0