1.数组排序,遍历数组,当元素发生跳变之前记录下元素的个数,如果大于数组的一半则返回该元素,否则继续遍历。
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
# write code here
count = 0
sorted_nums = sorted(numbers)
for i in range(len(sorted_nums)-1):
count += 1
if sorted_nums[i] != sorted_nums[i+1]:
if count > len(sorted_nums)/2.0:
return sorted_nums[i]
count = 0
return numbers[0] if len(numbers) == 1 else 02.使用一个target来记录当前的访问的值,如果下一个值与该值相同则count++,否则count--。如果count=0时更换target的值为当前值。如果数组中存在大于个数大于数组一半的值,target就是该值。
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
target = 0
count = 0
for num in numbers:
# 当count为0时,重置target和count
if count == 0:
target = num
count = 1
elif num == target:
count += 1
else:
count -= 1
# 判断target是否大于数组的一半
target_num = 0
for num in numbers:
if num == target:
target_num += 1
return target if target_num > len(numbers)/2.0 else 0 
京公网安备 11010502036488号