leetcode学习篇四——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.
难度:easy 通过率:43.7%

一开始看到题目,头脑发热,就直接写了一个分支法求最大值,然后才发现自己理解错题目了,是找出现次数大于数组大小一半的元素,所以可以确定这样的元素只有一个,于是就直接采用暴力解法,两次循环,时间复杂度O(n^2),代码如下,果真超时了……

int majorityElement(vector<int>& nums) {
    if(nums.size() == 1) return nums[0];
    for(int i = 0; i < nums.size(); i++) {
        int count = 0;
        for(int j = 0; j < nums.size(); j++) {
            if(nums[j] == nums[i]) {
                count ++;
            }
            if(count > nums.size()/2) {
                return nums[i];
            }
        }
    }
}

同样的思路,也是将每个数的数量计算出来,然后判断当数量大于数组大小一半时便返回,而考虑到以上做法对每个数都从头到尾计算数量,导致超时,所以考虑使用map在一次遍历中将每个数的数量记录下来,代码如下,因为find函数是通过二叉树实现,所以以下代码时间复杂度为O(nlogn).

class Solution {
public:
    int majorityElement(vector<int> &nums) {
        map<int, int> res;
        int result;
        for(int i = 0; i < nums.size(); i++) {
            map<int, int>::iterator it = res.find(nums[i]);
            if(it == res.end()) res[nums[i]] = 1;
            else res[nums[i]] ++;
            if(res[nums[i]] > nums.size() / 2) {
                return nums[i];
            } 
        }
        return 0;
    }
};

看了一下leetcode上面的讨论,通过Moore voting algorithm解决了这个问题,算法演示链接:点击此处
算法基本思想:每次在数组中找出一对不同的元素然后删除,因为Majority Element的次数大于一半,所以肯定最后剩下该元素,
算法复杂度:O(n),代码实现如下,

int majorityElement(vector<int> &nums) {
    int count = 0, result;
    for(int i = 0; i < nums.size(); i++) {
        if(count == 0) result = nums[i];
        if(result == nums[i]) count ++;
        else count--;
    }
    return result;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值