题目:
数组中 有一个数字出现次数超过数组长度的一半,请找出这个数字,比{1,2,3,2,2,2,2,5,4,2},数字2 在数组中出现了6次 ,超过了数组长度的一半。所以输出2
思路:
考虑一下,若一个数的数量超过了数组长度的一半,那么数组的中位数必然是该数字,换句话,我们只需找到排序数组的中位数即可 ,但如果先排序在找的话 hr肯定不会喜欢 ,所以我们要用一种高效的方式。
受快速排序的启发,随机找一个数,遍历数组,比他大的数放在他的右边,比他小的放在左侧。若该值正好为n/2处则输出,若该数下标大于n/2 则中位数在其左侧,再递归其左侧重复上诉步骤。若该数小于n/2则递归其右侧,
class Solution:
def MoreThanHalfNum_Solution(self, numbers):
l = len(numbers) - 1
mid_index = l//2
num_new = []
return self.sort_number(numbers, mid_index, numbers)
def sort_number(self,numbers, l, num_new):
left = []
right = []
mid = len(num_new)//2
mid_val = numbers[mid]
n = 0
for i in range(0,len(num_new)):
if numbers[i] < mid_val:
left.append(num_new[i])
elif num_new[i] > mid_val:
right.append(num_new[i])
elif num_new[i] == mid_val:
n = n+1
numbers = left +[mid_val]*n +right
#print(numbers, mid_val, len(left),len(right))
if n > len(right) + len(left):
if n > l:
return mid_val
else:
return 0
elif len(left) == len(right):
if n > l:
return mid_val
else:
return 0
elif len(left) < len(right):
return self.sort_number(numbers, l, right)
elif len(left) > len(right):
return self.sort_number(numbers, l, left)
if len(num_new) < 2:
if n > l:
return num_new[0]
else:
return 0
a = Solution()
b = a.MoreThanHalfNum_Solution([4,2,1,4,2,4])
print(b)