我是靠谱客的博主 超级白开水,这篇文章主要介绍Leetcode刷题笔记(c++)_剑指 Offer 39. 数组中出现次数超过一半的数字,现在分享给大家,希望可以做个参考。

排序

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(),nums.end());
        return nums[nums.size()/2];
    }
};

在这里插入图片描述

双指针

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n=nums.size();
        sort(nums.begin(),nums.end());
        int left=0,right=n-1;
        while(right>=left){
            if(nums[right]==nums[left])return nums[left];
            right--;
            left++;
        }
        return 0;
    }
};

在这里插入图片描述

哈希映射

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int n=nums.size();
        unordered_map<int,int>hashmap;
        for(int i:nums){
            hashmap[i]++;
            if(hashmap[i]>n/2)return i;
        }
        return 0;
    }
};

在这里插入图片描述

最后

以上就是超级白开水最近收集整理的关于Leetcode刷题笔记(c++)_剑指 Offer 39. 数组中出现次数超过一半的数字的全部内容,更多相关Leetcode刷题笔记(c++)_剑指内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(137)

评论列表共有 0 条评论

立即
投稿
返回
顶部