More than half of the number of other algorithms -028- digital array appears

Article Directory

Title Description

There are a number of array number that appears more than half the length of the array, find this number. For example, a length of the input array 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears five times, more than half the length of the array in the array, the output 2. If there is 0 output.

analysis

  • Method 1: Use python字典, each occurrence of a digital recording counter, and then traverse the results obtained, the time complexity O(n), the spatial complexity O(n). And this method may be 扩展as the array has a number of times exceeding the number that appears 任意次.

  • Method two: the array has a number of figures occurs more than half the length of the array, that is to say 它出现的次数比其他所有数字出现次数的和还要多. Therefore, we can consider saving two values through the array of time: one is a numeric array, a number of times.

    • When we traverse to the next digit when the next digit and if we previously saved numbers are the same, the number of plus 1;
    • If the next number and we saved before the numbers are different, then the number minus 1.
    • If the number is zero, we need to save the next number, and the number is set to 1.

Code

  • method one:
# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        dictH = {}
        length = len(numbers)
        for i in numbers:
            if i in dictH:
                dictH[i] += 1
            else:
                dictH[i] = 1
        
        for i in set(numbers):
            if dictH[i] > length/2:
                return i
        
        return 0
  • Method Two:
# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        if not numbers:
            return 0
        
        
        res = numbers[0]
        counter = 1
        length = len(numbers)
        
        
        for i in numbers[1:]:
            if i==res:
                counter += 1
            else:
                counter -= 1
                if counter == 0:
                    res = i
                    counter = 1
        
        if numbers.count(res)>length/2:
            return res
        return 0
Published 219 original articles · won praise 85 · Views 140,000 +

Guess you like

Origin blog.csdn.net/z_feng12489/article/details/103476996