两种方法

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

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
全部评论

相关推荐

点赞 评论 收藏
分享
认真搞学习:28小登的建议,投算法岗不要写什么物理竞赛,互联网+,多写点项目,用什么算法做了什么。还有本科算法是不可能的开发你这个也没有项目啊
点赞 评论 收藏
分享
06-23 11:43
门头沟学院 Java
allin校招的烤冷...:我靠,今天中午我也是这个hr隔一个星期发消息给我。问的问题还是一模一样的😅
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务