Skip to content

Commit 53e36ba

Browse files
author
Adam Lin
committed
unordered_map and set and iterator manipulation
1 parent 14d3edd commit 53e36ba

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

1207_uniqueOccurrences.cpp

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Solution {
2+
public:
3+
bool uniqueOccurrences(vector<int>& arr) {
4+
unordered_map<int, int> umap; // Map to store frequency of each element in arr
5+
set<int> frequency; // Set to store unique frequencies
6+
7+
// Count the frequency of each element in arr
8+
for(int i = 0; i < arr.size(); ++i){
9+
umap[arr[i]]++;
10+
}
11+
// Example: arr = [1,2,2,1,1,3] -> umap = {{1, 3}, {2, 2}, {3, 1}}
12+
13+
// Check if all frequencies are unique
14+
for(auto it : umap){
15+
// Check if the frequency already exists in the set
16+
if(frequency.find(it.second) != frequency.end()){
17+
// If the frequency already exists, it means the occurrences are not unique
18+
// frequency.find(value) searches the set for the given value.
19+
//If the value is found, it returns an iterator pointing to that element.
20+
//If the value is not found, it returns frequency.end(), which is a special iterator indicating the end of the set.
21+
return false; // Return false since we found a duplicate frequency
22+
}
23+
frequency.insert(it.second); // Insert frequency into set
24+
}
25+
26+
return true; // All frequencies are unique
27+
}
28+
};
29+
/*
30+
The variable it is actually an instance of std::pair<const int, int> because umap is an unordered_map<int, int>. Each element in an unordered map is stored as a key-value pair, where the key is of type int and the value is also of type int. Therefore, it represents a pair consisting of key and value.
31+
32+
For std::pair, you can access:
33+
34+
it.first which gives you the key.
35+
it.second which gives you the value (in this case, the frequency of the element).
36+
*/

0 commit comments

Comments
 (0)