两种方法

数组中出现次数超过一半的数字

http://www.nowcoder.com/questionTerminal/e8a1b01a2df14cb2b228b30ee6a92163

快速排序思想:

class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        def partition(num, start, end):
            pivot = start
            index = start + 1
            i = index
            while i <= end:
                if num[i] <= num[pivot]:
                    num[index], num[i] = num[i], num[index]
                    index += 1
                i += 1
            num[pivot], num[index-1] = num[index-1], num[pivot]
            return index-1
        if len(numbers) == 0:
            return 0
        start = 0
        end = len(numbers) - 1
        mid = end // 2
        index = partition(numbers, start, end)
        while index != mid:
            if index > mid:
                end = index - 1
                index = partition(numbers, start, end)
            else:
                start = index + 1
                index = partition(numbers, start, end)
        count = 0
        for i in numbers:
            if i == numbers[index]:
                count += 1
        if count*2 <= len(numbers):
            return 0
        return numbers[index]

投票法

class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        temp = numbers[0]
        count = 1
        for i in range(1, len(numbers)):
            if temp == numbers[i]:
                count += 1
            else:
                count -= 1
            if count == 0:
                temp = numbers[i]
                count = 1
        count = 0
        for i in numbers:
            if i == temp:
                count += 1
        if count*2 <= len(numbers):
            return 0
        return temp
全部评论

相关推荐

jack_miller:我给我们导员说我不在这里转正,可能没三方签了。导员说没事学校催的时候帮我想办法应付一下
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务