您的位置:首页 > 其它

LeetCode 169. Majority Element (数组的主要元素、摩尔投票算法)

2017-05-24 19:25 676 查看
4000

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向下取整)。

思路①将数组排序后,位于n/2向下取整位置的即为主要元素。

int majorityElement(vector<int>& nums) {
sort(nums.begin(),nums.end());
return nums[nums.size()/2];
}


思路②Moore's voting algorithm: 不断删去数组中两个不同的数,直到最后剩下的数都相同,即为主要元素。

public int majorityElement(int[] num) {

int major=num[0], count = 1;
for(int i=1; i<num.length;i++){
if(count==0){
count++;
major=num[i];
}else if(major==num[i]){
count++;
}else count--;

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