LeetCode:169. Majority Element

来源:互联网 发布:linux vsftpd使用 编辑:程序博客网 时间:2024/06/05 17:38

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次那么return,这种方法结果出现超时。上网查找一下,发现有个很好的 方法:每找出两个不同的element,就成对删除即count--,最终剩下的一定就是所求的。

AC:

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

0 0
原创粉丝点击