Python版:
class Solution:
def majorityElement(self, nums: List[int]) -> int:
temp = -1
c = 0
for l in nums:
if temp == -1:
temp = l
c = 1
else:
if c == 0:
temp = l
c = 1
elif temp == l:
c += 1
else:
c -= 1
return temp
Java版
class Solution {
public int majorityElement(int[] nums) {
int temp = -100;
int c = 0;
for(int i=0; i<nums.length; i++){
if(temp == -100){
temp = nums[i];
c = 1;
}else{
if(c == 0){
temp = nums[i];
c = 1;
}else if(temp == nums[i])
c += 1;
else{
c -= 1;
}
}
}
return temp;
}
}