More than half of the number 39. The array of digital face questions arise

Topic Description: The
array has a number of figures appear more than half the length of the array, find this number. You can assume that the array is non-empty, and there is always most elements of a given array.

Example 1:

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

1 problem-solving ideas:

Use Counter, note reading method tuple


Code 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 problem-solving ideas:

There must be known to the array number occurs more than half the length of the array of numbers, the numbers must be sorted to the median


Code 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))

Topic Source:
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 /

Published 378 original articles · won praise 43 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_43283397/article/details/105106754