Skip to content

Commit c137d69

Browse files
solves #2200: Find All K-Distant Indices in an Array in java
1 parent 4ee8916 commit c137d69

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -718,7 +718,7 @@
718718
| 2185 | [Counting Words With a Given Prefix](https://leetcode.com/problems/counting-words-with-a-given-prefix) | [![Java](assets/java.png)](src/CountingWordsWithAGivenPrefix.java) | |
719719
| 2190 | [Most Frequent Number Following Key In an Array](https://leetcode.com/problems/most-frequent-number-following-key-in-an-array) | [![Java](assets/java.png)](src/MostFrequentNumberFollowingKeyInAnArray.java) | |
720720
| 2194 | [Cells in a Range on an Excel Sheet](https://leetcode.com/problems/cells-in-a-range-on-an-excel-sheet) | [![Java](assets/java.png)](src/CellsInARangeOnAnExcelSheet.java) | |
721-
| 2200 | [Find All K-Distant Indices in an Array](https://leetcode.com/problems/find-all-k-distant-indices-in-an-array) | | |
721+
| 2200 | [Find All K-Distant Indices in an Array](https://leetcode.com/problems/find-all-k-distant-indices-in-an-array) | [![Java](assets/java.png)](src/FindAllKDistantIndicesInAnArray.java) | |
722722
| 2206 | [Divide Array Into Equal Pairs](https://leetcode.com/problems/divide-array-into-equal-pairs) | | |
723723
| 2210 | [Count Hills and Valleys in an Array](https://leetcode.com/problems/count-hills-and-valleys-in-an-array) | | |
724724
| 2215 | [Find the Difference of Two Arrays](https://leetcode.com/problems/find-the-difference-of-two-arrays) | | |

Diff for: src/FindAllKDistantIndicesInAnArray.java

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// https://leetcode.com/problems/find-all-k-distant-indices-in-an-array
2+
// T: O(N)
3+
// S: O(N)
4+
5+
import java.util.ArrayList;
6+
import java.util.List;
7+
8+
public class FindAllKDistantIndicesInAnArray {
9+
public List<Integer> findKDistantIndices(int[] array, int key, int k) {
10+
final List<Integer> result = new ArrayList<>();
11+
12+
for (int index = 0 ; index < array.length ; index++) {
13+
if (array[index] == key) {
14+
int startIndex = Math.max(result.isEmpty() ? 0 : result.get(result.size() - 1) + 1, index - k);
15+
int endIndex = Math.min(index + k, array.length - 1);
16+
for (int i = startIndex ; i <= endIndex ; i++) {
17+
result.add(i);
18+
}
19+
}
20+
}
21+
22+
return result;
23+
}
24+
}

0 commit comments

Comments
 (0)