Majority Element (leetcode)

Majority Element


题目

leetcode题目
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的给定数组的主元素(一定存在),而这个主元素的特征是在数组里面出现的次数大于 n/2


解决方案

1. 暴力解决

根据题目所给主元素的特征,我们可以将数组遍历一遍,之后将每个数的出现次数统计出来,出现次数最多的即为主元素。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        std::map<int, int> count;
        int nums_size = nums.size();
        map<int, int>::iterator it;
        /* 统计数组中每个数的出现次数 */
        for (int i = 0; i < nums_size; i++) {
            it = count.find(nums[i]); // 判断nums[i]是否出现过
            if (it == count.end()) { // 没出现过
                count[nums[i]] = 1;
            } else { // 出现过
                count[nums[i]]++;
            }
        }
        int max = 0;
        int result = 0;
        /* 找出出现次数最多的数 */
        for (int i = 0; i < nums_size; i++) {
            if (count[nums[i]] > max) {
                max = count[nums[i]];
                result = nums[i];
            }
        }
        return result;
    }
};

leetcode结果:44 / 44 test cases passed. Runtime: 23 ms

2. 排序解决

因为主元素在数组中的出现次数大于 n/2 ,所以将数组排序之后,数组最中间的数一定为主元素。
排序算法有很多种,不同的排序算法的性能不同。

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

leetcode结果:44 / 44 test cases passed. Runtime: 43 ms

3. Moore Voting Algorithm

这种方法是在网上了解到的。使用两个变量:result和 count这两个变量记录了元素result的值,count记录了元素result比其他元素多出现的次数。
遍历数组,遇到与当前记录元素result相同的元素值,count++;否则count–。当count变为0时,更换result为当前遍历所在的像素值。由于遍历完数组后,主元素被抵消的次数count比然大于零,不会因为当count变为0而被其他数组元素替代,因此result也只会是主元素。这种情况适用于主元素一定存在。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int number = nums.size();
        int result;
        int count = 0;
        for (int i = 0; i < number; i++) {
            if (count == 0) {
                result = nums[i];
                count++;
            } else {
                if (result == nums[i]) {
                    count++;
                } else {
                    count--;
                }
            }
        }
        return result;
    }
};

leetcode结果:44 / 44 test cases passed. Runtime: 19 ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值