I saw this code on leetcode,it's a question to find the majority element.Here is the question description:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
And there is an answer in discuss with these code:
class Solution
{
public:
int majorityElement(vector<int>& nums)
{
map<int, int> cnt;
for(int i=0; i < nums.size(); i++)
cnt[ nums[i] ]++;
int n = nums.size();
for(map<int, int>::iterator iter=cnt.begin(); iter!=cnt.end();iter++)
if( iter->second > n/2 )
return iter->first;
}
};
So I am curious about this line:cnt[ nums[i] ]++;
Don't I need to initialize the cnt[nums[i]]=0 first? I thought I need to do it first or there will be memory leakage because no existing value for key nums[i] to perform ++. Am I wrong?
std::map::operator[] is defined to default initialise the value at the given key if no such value already exists. From the standard; [map.access]:
T& operator[](const key_type& x);
1 Effects: If there is no key equivalent to x in the map, inserts value_type(x, T()) into the map.
For int, the default value is 0, so no further work must be done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With