剑指offer 数组中出现次数超过一半的数字 python实现

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        start = 0
        end = len(numbers) - 1
        index = self.qsort_rec(numbers, start, end)
        middle = int((start + end)/2)
        while index != middle:
            if index < middle:
                start = index + 1
                index = self.qsort_rec(numbers, start, end)
            else:
                end = index - 1
                index = self.qsort_rec(numbers, start, end)
        valid_num = 0
        for i in range(len(numbers)):
            if numbers[i] == numbers[middle]:
                valid_num += 1
        if valid_num <= int(len(numbers)/2):
            return 0
        return numbers[middle]
    def qsort_rec(self, lst, left, right):
        if left > right:
            return
        i = left
        j = right
        pivot = lst[i]
        while i < j:
            while i < j and lst[j] >= pivot:
                j -= 1
            if i < j:
                lst[i] = lst[j]
                i += 1
            while i < j and lst[i] <= pivot:
                i += 1
            if i < j:
                lst[j] = lst[i]
                j -= 1
        lst[i] = pivot
        return i

你可能感兴趣的:(数据结构)