Re: [閒聊] 每日leetcode

作者: smart0eddie (smart0eddie)   2024-08-05 14:58:13
2024-08-05
2053. Kth Distinct String in an Array
A distinct string is a string that is present only once in an array.
Given an array of strings arr, and an integer k, return the kth distinct
string present in arr. If there are fewer than k distinct strings, return an
empty string "".
Note that the strings are considered in the order in which they appear in the
array.
好像除了用 dict 去計數以外我不知道怎麼做欸
class Solution {
public:
string kthDistinct(vector<string>& arr, int k) {
unordered_map<string, int> count;
for (auto& s : arr) {
++count[s];
}
int curK = 0;
for (auto& s : arr) {
if (1 == count[s]) {
curK++;
}
if (curK == k) {
return s;
}
}
return "";
}
};

Links booklink

Contact Us: admin [ a t ] ucptt.com