leetcode Majority Element

来源:互联网 发布:python 3.0 哪些不同 编辑:程序博客网 时间:2024/05/21 06:33

题目: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.

这个数出现的次数大于其他所有数出现的次数

public class Solution {

    public int majorityElement(int[] num) {
        int count=1;
int seed=num[0];
int len=num.length;
for(int i=1;i<len;i++){
if(seed==num[i]){
count++;
}else if(count>0){
count--;
}else{
seed=num[i];
}
}//for
return seed;


    }
}
0 0
原创粉丝点击