169. Majority Element

来源:互联网 发布:fitbit手环哪款好 知乎 编辑:程序博客网 时间:2024/06/16 04:56

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的数组,找到多数元素。多数元素是出现次数 ⌊n/2⌋ 以上的元素。

您可以假定该数组不为空,并且多数元素始终存在于数组中。

解题思路

如果正常使用排序算法的话然后进行遍历的话时间复杂度达到了O(nlogn),这不是一个好的方式。
一共有两个思路都能达到O(n),第一个是用计数器,过半数的元素计数器最终一定会计数到它,代码如下

public class Solution {    public int majorityElement(int[] nums) {        int count=0;        int element=0;        for(int i=0;i<nums.length;i++){            if(count==0){                element=nums[i];                count=1;            }else{                if(element==nums[i]){                    count++;                }else{                    count--;                }            }        }        return element;    }}

另一个很神奇的思路是使用随机数,数学期望是2*O(n),也就是O(n),因为元素过半,所以每次随机数有50%的几率会选中该元素,所以时间复杂度也比较低,代码如下

class Solution {public:    int majorityElement(vector<int> &num) {        int count = 0;        for(;;) {            if(num.size() == 1)                return num[0];            else    {                int i = rand() % (num.size() - 1);                for(int j = 0; j < num.size(); j++) {                    if(num[j] == num[i])                        count++;                }                if(count > (num.size() / 2))                    return num[i];                else    {                    count = 0;                    continue;                }            }        }    }  };

欢迎加入中科院开源软件自习室:631696396

欢迎加入中科院开源软件自习室

原创粉丝点击