代码最简洁的就是排序法了,因为该数在数组中超过一半,排序后的数组中位一定是目标数字。
排序法
python实现
class Solution:
def MoreThanHalfNum_Solution(self , numbers: List[int]) -> int:
return sorted(numbers)[len(numbers) // 2]
c++实现
class Solution {
public:
int MoreThanHalfNum_Solution(vector<int> numbers) {
sort(numbers.begin(), numbers.end());
return numbers[numbers.size()/2];
}
};
哈希
python实现
class Solution:
def MoreThanHalfNum_Solution(self , numbers: List[int]) -> int:
if len(numbers) == 1:
return numbers[0]
dict_temp = {}
length = len(numbers)
for i in range(length):
now_num = numbers[i]
if numbers[i] not in dict_temp:
dict_temp[now_num] = 1
else:
dict_temp[now_num]+=1
if dict_temp[now_num] > length//2:
return now_num
return None