题目描述
时间复杂度 O(n) , 空间复杂度O(1)
JAVA 代码
public int moreThanHalfNum_Solution(int[] nums) {
int val = 0, count = 0;
for (int num : nums) {
if (count == 0){
count++;
val = num;
}else {
if (val == num){
count++;
}else {
count--;
}
}
}
count = 0;
for (int num : nums) {
if (num == val){
count++;
}
}
return count > nums.length >> 1 ? val : 0;
}