[leetcode] 169. Majority Element 解题报告

63 篇文章 0 订阅
2 篇文章 0 订阅

题目链接:https://leetcode.com/problems/majority-element/

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.

思路:本题有两种方法:

1.基于快速排序的分割算法,partition函数每次会把数组分成两个部分,并把一个值排在正确的位置,如果这个位置是在n/2处,则说明这个数必然是出现超过n/2次的数。这种方法同样可以处理寻找第K大的数。

代码如下:

class Solution {
public:
    int partition(vector<int>& nums, int low, int high)
    {
        int val = nums[high], k =low-1;
        for(int i = low; i < high; i++)
            if(nums[i] < val) swap(nums[i], nums[++k]);
        swap(nums[high], nums[++k]);
        return k;
    }
    
    int majorityElement(vector<int>& nums) {
        int len = nums.size(), low = 0, high = len -1, mid=len/2;
        while(low < high && (mid=partition(nums, low, high))!= len/2)
        {
            if(mid > len/2) high = mid-1;
            else low = mid+1;
        }
        return nums[len/2];
    }
};



2. 还有一种是BM投票算法,设置一个计数器,如果计数器为0,则统计当前数的个数,否则如果当前数等于要等于要统计的数则计数器加1,否则减一。

代码如下:

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int cnt = 0, num, len = nums.size();
        for(int i =0; i< nums.size(); i++)
        {
            if(cnt == 0) num = nums[i];
            cnt = (num == nums[i])?(cnt+1):(cnt-1);
        }
        return num;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值