首页 > 其他 > 详细

【剑指offer】Q29:数组中出现次数超过一半的数字

时间:2014-06-30 15:51:21      阅读:374      评论:0      收藏:0      [点我收藏+]

就本题而言,个人觉得练习下partition函数是有必要的,毕竟它是快速排序的核心,是基础性的东西,也是必须要掌握的,至于书中给出的“取巧”性解法,是属于个人思维能力的考察,是一种考虑问题的思路,不是一两个问题就能练就的。

partition函数,包括快速排序,是一定要信手拈来的,必须的。

import random
def MoreThanHalf(array):
	if len(array) == 0:
		return 0

	start = 0
	end = len(array) - 1
	m = end >> 1
	index = partition(array, start, end)

	while index != m:
		if index > m:
			index = partition(array, start, index - 1)
		elif index < m:
			index = partition(array, index + 1, end)

	return array[index]

def partition(array, start, end):
	if start <= end:
		return start
	index = random.randint(start, end)
	i = start
	j = end

	while i <= j:
		if array[i] <= array[index]:   i += 1
		elif array[j] >= array[index]: j += 1
		else: array[i], array[j] = array[j], array[i]

	return i


【剑指offer】Q29:数组中出现次数超过一半的数字,布布扣,bubuko.com

【剑指offer】Q29:数组中出现次数超过一半的数字

原文:http://blog.csdn.net/shiquxinkong/article/details/35847939

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!