The number that appears more than half the number of times in the array of "Sword Finger Offer"

The number that appears more than half the number of times in the array of "Sword Finger Offer"

I don't know where I am going, but I am already on my way!
Time is hurried, although I have never met, but I met Yusi, it is really a great fate, thank you for your visit!
  • Question : The
    number of occurrences of a number in the array exceeds half of the length of the array. Please find out this number. For example, enter an array {1,2,3,2,2,2,5,4,2} with a length of 9. Since the number 2 appears 5 times in the array, which is more than half the length of the array, 2 is output. If it does not exist, output 0.
  • Example :
示例 1 :
输入:[1,2,3,2,2,2,5,4,2]
返回值:2
  • Code 1:
# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        length = len(numbers) // 2
        result = {
    
    }
        for i in numbers:
            if i not in result:
                result[i] = 1
            else:
                result[i] += 1
            if result[i] > length:
                return i
        return 0
  • Algorithm description:
    Find half the length of the array and create an empty dictionary;
    traverse the array elements one by one. If the current element is not in the dictionary, store the current element in the dictionary with the key value set to 1.
    If the current element is in the dictionary, set The key value +1;
    if the key value exceeds half the length, the current element is returned, otherwise it returns 0.

Guess you like

Origin blog.csdn.net/qq_34331113/article/details/115058390