【LeetCode】Majority Element(求主元素)

说明

这道题出现在了王道的《2019数据结构考研复习指导》的18页,LeetCode中也有这道题。题目大意是:给定一个长度为n的数组,我们定义"主元素"为数组中出现次数超过⌊n/2⌋的元素。

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.

Example 1:

Input: [3,2,3]
Output: 3

Example 2:

Input: [2,2,1,1,1,2,2]
Output: 2

解析

设数组为nums, 主元素为data,主元素出现的次数为count;

  1. 假设第一个元素可能成为主元素,则data = nums[0],count=1
  2. i = i + 1, 比较nums[i]是否等于当前的主元素data,如果相等则说明data出现的次数又多了一次,count = count + 1;如果不相等,则让count = count - 1
  3. 如果count为0, 让data = nums[i](假设为主元素)
  4. 重复2、3步,直到遍历完所有的元素。
  5. 如果count > 0,遍历所有的元素,统计出值等于data的元素的个数c,如果元素个数c大于 > n/2,则说明data是该数组的主元素。

此算法的基本思想就是如果某个元素是数组nums的主元素,则它出现的次数一定大于数组元素的一半,且一定是最后一个重置data的元素。
时间复杂度: O(n),空间复杂度: O(1)

C++实现

#include <iostream>
#include <vector>
using namespace std;
int majorityElement(vector<int> &nums);
int main()
{
    int n;
    vector<int> nums;
    cin >> n;   // 第一行输入n(元素的总数)
    while (n--) // 依次读取n个数字
    {
        int t;
        cin >> t;
        nums.push_back(t);
    }
    int element = majorityElement(nums);
    cout << element;
    return 0;
}
int majorityElement(vector<int> &nums)
{
    if (nums.empty())
        return -1;
    if (nums.size() == 1)
        return nums[0];
    int count = 1;
    int data = nums[0];
    for (int i = 1; i < nums.size(); ++i)
    {
        if (data == nums[i])
            count++;
        else
            count--;
        if (count == 0)
        {
            data = nums[i];
            count = 1;
        }
    }
    int c = 0;
    if (count > 0)
    {
        for (int i = 0; i < nums.size(); ++i)
        {
            if (data == nums[i])
                c++;
        }
    }
    if (c > nums.size() / 2)
        return data;
    else
        return -1;
}


本作品采用知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议进行许可。转载请注明: 作者staneyffer,首发于我的博客,原文链接: https://chengfy.com/post/7

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 1. Remove Duplicates from Sorted Array Description: Easy ...
    BookThief阅读 3,800评论 0 1
  • 鉴峰自我管理 [连续签到第87天] 2018-4-5 周二 鉴峰笔记之清明: 你我点一盏心灯。 照亮天堂的路, 让...
    鉴峰笔记阅读 876评论 0 0
  • 通过放下自我与成为自己,达到“合一感”的境界,做真实的自己。
    DDM王军燕阅读 682评论 0 0
  • 萧骁是一个傲气而自卑的人,她不甘落于人后,永远高高昂起头挺直腰,却又因容颜与过往退却。但周围所有人都认为她阳...
    荒鸦阅读 1,638评论 0 0