C++学习笔记---再探 map 的用法之计数重复key的value值的方法,由leetcode 169题想到的

先描述下leetcode 169题的题目:
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

方法一:利用map的性质

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        map<int,size_t> value;
        for(int i=0;i<nums.size();i++)
        {
            ++value[nums[i]];
        }
        auto map_it=value.begin();
        while(map_it!=value.end())
        {
            if ((map_it->second)>(floor(nums.size()/2)))
            {
                break;
            }
            else
              ++map_it;
        }
        return map_it->first;
    }
};

方法二:利用insert的返回值

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        map<int,size_t> value;
        for(int i=0;i<nums.size();i++)
        {
            auto ret=value.insert({nums[i],1});
            if(!ret.second)
              ++ret.first->second;
        }
        auto map_it=value.begin();
        while(map_it!=value.end())
        {
            if ((map_it->second)>(floor(nums.size()/2)))
            {
                break;
            }
            else
              ++map_it;
        }
        return map_it->first;
    }
};

方法三:利用insert的返回值的传统写法,及其本质探究

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        map<int,size_t> value;
        pair<map<int,size_t>::iterator,bool> ret;
        for(int i=0;i<nums.size();i++)
        {
            ret=value.insert({nums[i],1});
            if(!ret.second)
              ++ret.first->second;
        }
        auto map_it=value.begin();
        while(map_it!=value.end())
        {
            if ((map_it->second)>(floor(nums.size()/2)))
            {
                break;
            }
            else
              ++map_it;
        }
        return map_it->first;
    }
};

从旧版的定义我们知道insert的返回值ret的类型为:

pair<map<int,size_t>::iterator,bool>

map的特性是这样的,当key value相同时,第二次以及以后出现的key value进行的insert操作均是无效的
所以ret->second 为 false,

set.first->second // 则指代map中的size_t

所以 if 中的语句代表当map中有key 重复时 value 值自加1

猜你喜欢

转载自blog.csdn.net/laoma023012/article/details/52107069
今日推荐