面试题39. 数组中出现次数超过一半的数字

题目描述:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。你可以假设数组是非空的,并且给定的数组总是存在多数元素。

示例 1:

输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2

解题思路1:

使用Counter,注意元组的读取方式


代码1:

class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        if not numbers:  return 0
        count = Counter(numbers).most_common()  # [(2, 5), (1, 1), (3, 1), (5, 1), (4, 1)]
        if count[0][1] > len(numbers) / 2:
            return count[0][0]
        return 0

s = Solution()
numbers = [1,2,3,2,2,2,5,4,2]
print(s.MoreThanHalfNum_Solution(numbers))

解题思路2:

已知数组中一定存在出现次数超过数组长度一半的数字,那么排序后该数字一定是中位数


代码2:

class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        if not numbers:  return 0
        count = sorted(numbers)
        return count[len(numbers)//2]

s = Solution()
numbers = [1,2,3,2,2,2,5,4,2]
print(s.MoreThanHalfNum_Solution(numbers))

题目来源:
https://leetcode-cn.com/problems/shu-zu-zhong-chu-xian-ci-shu-chao-guo-yi-ban-de-shu-zi-lcof/solution/pai-xu-qu-zhong-zhi-by-xin-ru-zhi-shui-33/

发布了378 篇原创文章 · 获赞 43 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_43283397/article/details/105106754
今日推荐