码迷,mamicode.com
首页 > 编程语言 > 详细

剑指Offer 28. 数组中出现次数超过一半的数字 (数组)

时间:2018-10-15 14:42:12      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:二次   pytho   次数   odi   有一个   class   coding   res   dict   

题目描述

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

题目地址

https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?tpId=13&tqId=11181&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路

思路1:使用hash函数,第一次遍历将每个数字出现次数保存下来,第二次遍历寻找次数超过数组长度一半的数字。

思路2:如果有符合条件的数字,则它出现的次数比其他所有数字出现的次数和还要多。

在遍历数组时保存两个值:一是数组中一个数字,一是次数。遍历下一个数字时,若它与之前保存的数字相同,则次数加1,否则次数减1;若次数为0,则保存下一个数字,并将次数置为1。遍历结束后,所保存的数字即为所求。然后再判断它是否符合条件即可。

Python

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        if len(numbers) == 0:
            return 0
        # 思路1
        # dict = {}
        # for x in numbers:
        #     if x not in dict:
        #         dict[x] = 1
        #     else:
        #         dict[x] += 1
        # for key, val in dict.items():
        #     if val > len(numbers)//2:
        #         return key
        # return 0
        # 思路2
        result = numbers[0]
        time = 1
        for i in range(1,len(numbers)):
            if time == 0:
                result = numbers[i]
                time = 1
            elif numbers[i] == result:
                time += 1
            else:
                time -= 1
        # 判断result是否符合条件,即出现次数大于数组长度的一半
        time = 0
        for i in range(len(numbers)):
            if numbers[i] == result:
                time += 1
        if time > len(numbers)//2:
            return result
        else:
            return 0
if __name__ == __main__:
    result = Solution().MoreThanHalfNum_Solution([1,2,3,2,2,2,5,4,2])
    print(result)

剑指Offer 28. 数组中出现次数超过一半的数字 (数组)

标签:二次   pytho   次数   odi   有一个   class   coding   res   dict   

原文地址:https://www.cnblogs.com/huangqiancun/p/9790076.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!