-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2053.KthDistinctStringInAnArray.cpp
More file actions
48 lines (40 loc) · 1001 Bytes
/
2053.KthDistinctStringInAnArray.cpp
File metadata and controls
48 lines (40 loc) · 1001 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Solution {
public:
string kthDistinct(vector<string>& arr, int k) {
// Speed thingies.
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// Calculation variables.
const int n = arr.size();
// Scan information.
int usedIndex = 0;
unordered_map<string, int> used;
// Find kth distinct.
int i;
for (i = 0; i < n; i++) {
const string& target = arr[i];
// Update used map.
for (; usedIndex < n; usedIndex++) {
const string& found = arr[usedIndex];
const auto foundIt = used.find(found);
if (foundIt == used.end()) {
// Create entry.
used.emplace(found, 1);
continue;
}
// Update entry.
foundIt->second++;
// We can continue later when we need it.
if (found == target && foundIt->second > 1) break;
}
// Check if target is distinct.
auto it = used.find(target);
if (it->second > 1) continue;
// Count to k.
k--;
if (k <= 0) break;
}
return i < n ? arr[i] : "";
}
};