Easy
Related Topics: Array / Hash Table / String / Counting
LeetCode Source
透過一個 hash map 來計算每個 string 出現的次數
之後透過這個 hash map 藉由 arr
的值之順序 access hash map
判斷 hash map 的 value 為一時紀錄 count
當 count
值跟 k
相同時回傳當前 hash map 的 key 值
若沒找到則會回傳預設 ""
空字串
Time Complexity: O(n)
Space Complexity: O(n)
class Solution:
def kthDistinct(self, arr: List[str], k: int) -> str:
dict = {}
for i in arr:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
count = 0
for key, val in dict.items():
if val == 1:
count += 1
if count == k:
return key
return ""
class Solution {
public:
string kthDistinct(vector<string>& arr, int k) {
unordered_map<string, int> mp;
int count = 0;
for (auto i : arr) {
auto it = mp.find(i);
if (it != mp.end())
mp[i] += 1;
else
mp[i] = 1;
}
for (int i = 0; i < arr.size(); i++) {
if (mp[arr[i]] == 1) {
count += 1;
if (count == k)
return arr[i];
}
}
return "";
}
};