您的位置:首页 > 其它

LeetCode|Majority Element *

2016-04-18 19:46 316 查看

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.

思路:

因为出现次数最多的数的数量比其他所有数的个数的和还多,所以遇见不同的两个数就丢弃。最后还能剩下来的就是数量最多的那个。

代码:

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


Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

思路:

代码:

这里写代码片
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: