[LeetCode]169.Majority Element

160 篇文章 28 订阅
【题目】

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 ⌋就返回

【代码】

/*********************************
*   日期:2015-01-30
*   作者:SJF0115
*   题目: 169.Majority Element
*   网址:https://oj.leetcode.com/problems/majority-element/
*   结果:AC
*   来源:LeetCode
*   博客:
**********************************/
#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    int majorityElement(vector<int> &num){
        int len = num.size();
        int size = len / 2 + 1;
        int count;
        // 统计前一半的元素个数
        for(int i = 0;i < size;++i){
            // 跳过重复元素
            while(i > 0 && num[i] == num[i-1]){
                ++i;
            }//while
            count = 0;
            for(int j = i;j < len;++j){
                if(num[j] == num[i]){
                    ++count;
                    if(count >= (len+1)/2){
                        return num[i];
                    }//if
                }//if
            }//for
        }//for
    }
};

int main(){
    Solution solution;
    vector<int> num = {8,8,7,7,7};
    int result = solution.majorityElement(num);
    // 输出
    cout<<result<<endl;
    return 0;
}


【分析二】

Every number in the vector votes for itself, the majority number gets the most votes. Different number offsets the votes.

遇到不同的就相互抵销,遇到相同的就增加,当count = 0时,重新开始

【代码二】

class Solution {
public:
    int majorityElement(vector<int> &num){
        int vote = num[0];
        int count = 1;
        int size = num.size();
        //vote from the second number
        for(int i = 1;i < size;++i){
            if(count == 0){
                vote = num[i];
                count++;
            }//if
            else if(vote == num[i]){
                count++;
            }
            else{
                count--;
            }
        }//for
        return vote;
    }
};

【分析】

Majority Element肯定占据至少一半的元素,因此排序后中间元素一定是Majority Element

【代码】

class Solution {
public:
    int majorityElement(vector<int> &num){
        int size = num.size();
        // 只有一个元素
        if(size == 1){
            return num[0];
        }//if
        sort(num.begin(),num.end());
        return num[size / 2];
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@SmartSi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值