gpt4 book ai didi

c++ - map 计数器;计数器[nums[i]]++;

转载 作者:太空狗 更新时间:2023-10-29 20:55:29 29 4
gpt4 key购买 nike

我在leetcode上看到这段代码,是一道求众数的题,下面是题目描述:

给定一个大小为 n 的数组,找到多数元素。众数元素是出现次数超过 ⌊ n/2 ⌋ 次的元素。

你可以假设数组是非空的并且多数元素总是存在于数组中。

讨论这些代码有一个答案:

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;
}
};

所以我很好奇这一行:cnt[ nums[i] ]++;

我不需要先初始化 cnt[nums[i]]=0 吗?我想我需要先做,否则会出现内存泄漏,因为键 nums[i] 没有现有值来执行++。我错了吗?

最佳答案

std::map::operator[] 被定义为默认初始化给定键处的值(如果不存在这样的值)。从标准; [ map 访问]:

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.

对于int,默认值为0,因此无需做进一步的工作。

关于c++ - map<int,int> 计数器;计数器[nums[i]]++;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35617844/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com