剑指offer39
1. 解法1
class Solution:
def majorityElement(self, nums: List[int]) -> int:
count = collections.Counter(nums)
return max(count.keys(),key = count.get)
2. 解法2
摩尔投票法:每次从序列里选择两个不相同的数字抵消掉,最后只剩下相同的数字,就是出现次数大于总数一半的那个。摩尔算法详解
public class Solution {
public int MoreThanHalfNum_Solution(int [] array) {
int count=0; // 次数
Integer card = null;
for(int num:array){
if(count==0){
card =num;
}
count +=(card==num)?1:-1;
}
return card;
}
}
// 遍历数组元素,若当前元素和已保存数字相同,则次数加1,反之则减1
// 若次数为0,则保存下一个元素,、