Leetcode-169-Majority Element

来源:互联网 发布:java调用so库 编辑:程序博客网 时间:2024/04/29 12:31

Leetcode-169-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.

题目的要求是找到一个数组中出现次数超过⌊ n/2 ⌋次的数(主元素),n是数组中元素的个数。假设该数一定存在。

最基本的方法是两重循环,遍历查找,直到找到某个数个数符合条件为止。复杂度为O(n2).

第二种方法是排序,通过排序得到中间位置的数即为所求。快排O(nlogn)

第三种方法是使用map,统计每个元素的个数。一旦某元素出现,对应value++。

最后主要介绍Moore's Voting algorithm算法,该算法可以在O(n)的时间内找到所求的结果。

当n个元素中,严格超过一半的数相同,那么它的出现频率比其余所有元素出现频率的总和还要大。也就是该主元素可以抵消所有其他元素后被留下。

那么我们设置一个候选元素e,以及计数器cnt,遍历数组,当出现的元素和e相同,则cnt++,当候选元素和主元素不同,则cnt--,进行抵消;直到cnt==0时,更换主元素,重复以上。

当遍历结束后,留下的e即为想要的结果。(若题目中未说明一定存在该值,则需要验证结果是否满足出现超过⌊ n/2 ⌋次)

代码如下:

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


0 0
原创粉丝点击