leetcode 169 Majority Element

来源:互联网 发布:websocket java 案例 编辑:程序博客网 时间:2024/04/29 09:58

题目描述:
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.
本题非常简单,写出来主要是方便准备面试的同学,这道题在面试题中出现的概率十分高,所以这里说明一下思路。

O(nlogn)的算法很容易实现,排序一下基本就OK,但是这种思路并不满足面试官的要求,通常会要求O(n)的思路。
观察数组就会发现一个很有趣的现象,达到majority要求的元素,总会出现位置相邻的情况,我们利用这个特点,对数组进行遍历,即可得到最后的结果。
代码实现如下(C++11):
class Solution {
public:
int majorityElement(vector<int>& nums) {
int count = 1;
if(nums.size()==0)
return 0;
int max = nums[0];
for(int i = 1;i<nums.size();i++) {
if(nums[i]==max) {
count++;
}else {
count--;
}
if(count<=0) {
max = nums[i];
count = 1;
}
}
if(count>0) {
count = 0;
for(auto&val:nums) {
if(val == max)
count++;
}
}
if(count>nums.size()/2)
return max;
return 0;
}
};

0 0
原创粉丝点击