题解 | #数组中出现次数超过一半的数字#

数组中出现次数超过一半的数字

http://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163

1、先找到元素出现的次数
2、找到大于一般出现的元素
3、找出最大的次数

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        count_map = {}
        numbers_len = len(numbers)

        for n in range(numbers_len):
            if numbers[n] not in count_map:
                count_map[ numbers[n] ] = 1
            else:
                count_map[ numbers[n] ] = count_map[ numbers[n] ]  + 1

        max_count_map = {}
        max_flag = ''
        max_flag_count = 0
        print(count_map)
        for i in count_map.items():
            if i[1] >= (numbers_len  // 2):
                print('big than')
                if max_flag == '':
                    max_flag = i[0]
                    max_flag_count =  i[1]
                    print(max_flag)
                else:
                    if i[1] > max_flag_count:
                        max_flag_count = i[1]
                        max_flag = i[0]
                        print('big than compare')
        print(max_flag,max_flag_count)
        return max_flag


if __name__ == '__main__':
    Solution().MoreThanHalfNum_Solution([2,2,2,3,3,3,3])
全部评论

相关推荐

我见java多妩媚:大外包
点赞 评论 收藏
分享
孤寡孤寡的牛牛很热情:为什么我2本9硕投了很多,都是简历或者挂,难道那个恶心人的测评真的得认真做吗
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务