(算法分析Week1)Majority Element[Easy]

169. Majority Element[Easy]

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.
找出数组中出现次数超过n/2次的数(n为数组元素总数)

Solution

方法一:哈希表
看到题目第一个想法就是哈希表,C++的map刚好合适,key:value(数组元素-出现次数),当某个元素出现次数大于n/2,直接返回。
方法二:排序
将数组元素从小到大排序,若存在majority element,必然出现在中间位置。
方法三:Moore Voting Algorithm

每次都找出一对不同的元素,从数组中删掉,直到数组为空或只有一种元素。 不难证明,如果存在元素e出现频率超过半数,那么数组中最后剩下的就只有e。

Discuss还有很多方法
6 Suggested Solutions in C++ with Explanations

Complexity analysis

方法一:遍历一次整个数组,时间复杂度O(n)
方法二:和sort采用的方法有关
方法三:遍历一次整个数组,时间复杂度O(n)

Code

方法一:

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

方法二:
//以SLT的sort为例

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 element = nums[0];
        int count = 1;
        for (int i = 1; i < nums.size(); i++) {
            if (element == nums[i]) {
                count++;
            }else if(count == 0) {
                count++;
                element = nums[i];
            } else {
                count--;
            }
        }
        return element;
    }
};

Result

从下往上分别是方法一、方法二、方法三。
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值