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

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

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])
全部评论

相关推荐

11-11 14:21
西京学院 C++
Java抽象练习生:教育背景放最前面,不要耍小聪明
点赞 评论 收藏
分享
爱看电影的杨桃allin春招:我感觉你在炫耀
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务