28.数组中出现次数超过一半的数字
题目描述
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
# -*- coding:utf-8 -*-
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
dict = {}
for no in numbers:
if not dict.has_key(no):
dict[no] = 1
else:
dict[no] = dict[no] + 1
if dict[no] > len(numbers)/2:
return no
return 0
链接:https://www.nowcoder.com/questionTerminal/e8a1b01a2df14cb2b228b30ee6a92163
来源:牛客网
python的三种解法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | # -*- coding:utf-8 -*- class Solution: """ 第一种,用python的标准库collections""" def MoreThanHalfNum_Solution(self, numbers): # write code here from collections import Counter count = Counter(numbers).most_common() if count[0][1] > len(numbers)/2.0: return count[0][0] return 0 class Solution : """ 第二种,假设有这个数字,那么它的数量一定比其它所有数字之和还要多,按照这个思路得出num,然后验证 """ def MoreThanHalfNum_Solution(self, numbers): # write code here if not numbers: return 0 num = numbers[0] count = 1 for i in range(1, len(numbers)): if numbers[i] == num: count += 1 else: count -= 1 if count == 0: num = numbers[i] count = 1 count = 0 for i in numbers: if i == num: count += 1 return num if count > len(numbers) / 2.0 else 0 class Solution: """ 对列表排序,计算下标为len/2(即中间位置)的数字数量即可""" def MoreThanHalfNum_Solution(self, numbers): # write code here # 对列表进行快排 left = 0 right = len(numbers) - 1 stack = [right, left] while stack: low = stack.pop() high = stack.pop() if low >= high: continue less = low - 1 mid = numbers[high] for i in range(low, high): if numbers[i] <= mid: less += 1 numbers[less], numbers[i] = numbers[i], numbers[less] numbers[less + 1], numbers[high] = numbers[high], numbers[less + 1] stack.extend([high, less+2, less, low]) # 验证 count = 0 length = len(numbers) // 2 for i in numbers: if i == numbers[length // 2]: count += 1 return numbers[length // 2] if count > length / 2.0 else 0 |