本文算法使用python3实现


1 题目描述:

  数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。
  时间限制:1s;空间限制:32768K


2 思路描述:

  方法一:新建一个字典,用来保存每次数字以及数字出现的次数,只不过这里考虑在每次对已存在的数字次数进行加一操作前,会先判断是否已满足条件,若已经满足条件则直接跳出,不再需要继续遍历
  方法二:使用res来保存当前数字,times来保存出现的次数。遍历数组,若遍历到的数字与res相同,则times加一,若不同则times减一。遍历完成后,res保存的数字即为所求。对于这种方法我们可以这样想,由于题目要求是超过数组长度一半,因此,即使该数字在数组中分布不均匀,但其出现的次数总是大于剩余其它数字出现次数总和。而最终times的值即为所求数字的出现次数与剩余其它数字出现次数总和的差值


3 程序代码:

(1)方法一

class Solution:
	def MoreThanHalfNum_Solution(self, numbers):
		if numbers == []:
			return 0
		if len(numbers) == 1:
			return numbers[0]
		lens = len(numbers)
		BreakFlag = lens / 2.0
		currentCount = {}
		for i in range(lens):
			# 如果当前数字在之前出现过,个数加一
			if numbers[i] in currentCount.keys():
				if currentCount[numbers[i]] + 1 > BreakFlag:
					return numbers[i] 
				currentCount[numbers[i]] += 1
			else: currentCount[numbers[i]] = 1
		return 0



(2)方法二:

class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        if not numbers: return 0
        res = 0
        times = 0
        for i, num in enumerate(numbers):
            if times == 0:
                res = num
                times = 1
            elif num == res:
                times += 1
            else:
                times -= 1
        return res if numbers.count(res) > len(numbers) / 2 else 0

相关文章:

  • 2021-09-26
  • 2021-08-10
  • 2022-01-09
  • 2021-08-17
  • 2021-07-22
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-06-29
  • 2021-06-28
  • 2021-12-11
  • 2021-06-11
  • 2021-10-22
  • 2022-12-23
相关资源
相似解决方案