Majority Element

来源:互联网 发布:编写java游戏小程序 编辑:程序博客网 时间:2024/06/07 04:18

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.

 Divide and Conquer Array Bit Manipulation

这道题的解法很多,官方推荐解法如下:


我这里主要实现【二种方法】:

1.sort方法:(nlogn)

思路:.

默认升序排序,取len/2即中点,值肯定为the majority element

<span style="white-space:pre"></span>//sort:时间复杂度O(nlogn)。最漂亮的解,不是最优解int majorityElement0(vector<int>& nums) {int len = nums.size();sort(nums.begin(), nums.end());return nums[len / 2];}

2.Moore voting algorithm(摩尔投票算法): (o(n))

思路:

1.投票人数n和候选人都初始化0;

 2.当n = 0,重新给候选人赋值;

 3.遍历完后,候选人肯定为the majority element。(因为element>n/2

<span style="white-space:pre"></span>
<span style="white-space:pre"></span>int majorityElement(vector<int>& nums) {<span style="white-space:pre"></span>int len = nums.size();int n = 0, candidate = 0;for (int i = 0; i < len; i++){if (n == 0){candidate = nums[i];n++;}else{if (candidate == nums[i])n++;else n--;}}if (n > 0)return candidate;}


0 0