Majority Number 解题报告

这篇博客主要介绍了如何找到数组中出现次数超过一半的元素,即Majority Number。利用投票算法,假设第一个数为vote并初始化计数器count,后续遍历数组时,若元素与vote相等则count加一,否则根据count是否为0来更新vote。这种方法能确保最终找到的vote是Majority Number,因为非Majority Number会被替换掉,而Majority Number不会。博客提供了java和python两种实现方式。
摘要由CSDN通过智能技术生成

Majority Number

Description

Given an array of integers, the majority number is the number that occurs more than half of the size of the array. Find it.

It should support push, pop and min operation all in O(1) cost.

Notice

You may assume that the array is non-empty and the majority number always exist in the array.

Example

Given [1, 1, 1, 1, 2, 2, 2], return 1

实现思路

这道题基于投票算法,
我们先假设数组nums中第一个数nums[0]就是我们要找的数vote,同时维护一个count变量,在后面判断中,如果nums[i] == vote(i=1….nums.length-1),则count++,如果不等,分两种情况:
1. 如果count > 0,则count–
2. 如果count = 0,则更新vote = nums[i]
为什么这样能得到我们要求的数major?我们可以这样分析:
对于任意一个数组nums中不等于major的数,基于我们的算法,它最终一定会被替换。因为它们的count(不超过一半)必定会在major(count大于一半)的不等判断下,被替换
那major会不会被替换呢?可能中间过程会,但遍历到最后,留下的必定是major。
根据此思路,求解方法如下:

java实现

public class Solution {
    /**
     * @param nums: a list of integers
     * @return: find a  majority number
     */
    public int majorityNumber(ArrayList<Integer> nums) {
        // write your code
        int vote = nums.get(0);
        int count = 1;
        for(int i = 1 ; i < nums.size(); i ++){
            if(nums.get(i) == vote){
                count ++;
            }else if(count == 0){
                vote = nums.get(i);
            }else{
                count --;
            }
        }
        return vote;
    }
}

python实现

class Solution:
    """
    @param nums: A list of integers
    @return: The majority number
    """
    def majorityNumber(self, nums):
        # write your code here
        if not nums:
            return None
        vote = nums[0]
        count = 0
        for num in nums:
            if num == vote:
                count += 1
            elif count == 0:
                vote = num
            else:
                count -= 1
        return vote
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值