2053. Kth Distinct String in an Array
2053. Kth Distinct String in an Array
1 | A distinct string is a string that is present only once in an array. |
难度 : Easy
思路
先用HashMap来记录每个string出现的次数然后遍历数组得到第k个distinct的string
注意edge case: 如果k非常大直接返回””.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class Solution {
public String kthDistinct(String[] arr, int k) {
if (k > arr.length) {
return "";
}
Map<String, Integer> counts = new HashMap<>();
for (String str : arr) {
int cnt = counts.getOrDefault(str, 0) + 1;
counts.put(str, cnt);
}
int index = 1;
for (int i = 0; i < arr.length && index <= k; i++) {
if (counts.get(arr[i]) == 1) {
if (index == k) {
return arr[i];
}
index++;
}
}
return "";
}
}