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