剑指offer 28. 数组中出现次数超过一半的数字

原题

题目:
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。

Reference Answer

思路分析

  1. 首先确定超过字符长度一半的元素:先排序,取出数值中间数值;
  2. 检查是否是真正超过字符长度一半:遍历数组进行该值出现次数计数,完成鉴定。
# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        if not numbers:
            return 0
        index = int(len(numbers)/2)
        count = 0
        numbers.sort()
        target = numbers[index]
        for x in numbers:
            if x == target:
                count+=1
        if count > index:
            return target
        else:
            return 0
            

简化版:

上述方法太繁琐了,下面提供个简化版:

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        import collections
        res = collections.defaultdict(int)
        for index, count in enumerate(numbers):
            res[count] += 1
            if res[count] > len(numbers) / 2:
                return count
        return 0

虽然是简化版,但是时间复杂度、空间复杂度依旧都是 O(n);可对空间复杂度进一步优化为 O(1)。

优化版:

思路:

数组中有一个数字出现的次数超过数组长度的一半,也就是说它出现的次数比其他所有数字出现次数的和还要多。因此我们可以考虑在遍历数组的时候保存两个值:一个是数组的一个数字,一个是次数。当我们遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数加1;如果下一个数字和我们之前保存的数字不同,则次数减1。如果次数为零,我们需要保存下一个数字,并把次数设为1。由于我们要找的数字出现的次数比其他所有数字出现的次数之和还要多,那么要找的数字肯定是最后一次把次数设为1时对应的数字。

Python Version:

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        if not numbers:
            return 0
        if len(numbers) == 1:
            return numbers[0]
        base = numbers[0]
        times = 1
        for count in numbers[1:]:
            if times == 0:
                base = count
            if count == base:
                times += 1
            else:
                times -= 1
        times = 0
        for count in numbers:
            if count == base:
                times += 1
        return base if times > len(numbers)/2 else 0
            

C++ Version:

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        if (numbers.empty()){
            return 0;
        }
        if (numbers.size() == 1){
            return numbers[0];
        }
        int base = numbers[0];
        int times = 1;
        for(int i=0; i < numbers.size(); i++){
            if (times == 0){
                base = numbers[i];
            }
            if (base == numbers[i]){
                times ++;
            }
            else{
                times --;
            }
        }
        times = 0;
        for(int i=0; i < numbers.size(); i++){
            if (numbers[i] == base){
                times ++;
            }
        }
        return (times > numbers.size()/2)? base: 0;
    }
};

对应时间复杂度为 O(n),空间复杂度为 O(1)。

Note:

再次强调,对dict的排序方式:

  • 对 value: sorted(dict.items(), key = lambda x:x[1])
  • 对 key: sorted(dict.items(), key = lambda x:x[0])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值