一种时间复杂度O(n) 空间复杂度O(1)的方法
提交代码
class Solution {
public int majorityElement(int[] nums) {
int candidate=nums[0], votes=1;
for(int i=1,len=nums.length;i<len;i++) {
if(nums[i]==candidate) votes++;
else if(votes==0) candidate=nums[i];
else votes--;
}
return candidate;
}
}
原理
可以看我的这篇博客