zoukankan      html  css  js  c++  java
  • 【leetcode】229. 求众数 II

    int* majorityElement(int* nums, int numsSize, int* returnSize){
        int* res =(int*)calloc(2,sizeof(int));
        *returnSize=0;
        if (nums == NULL || numsSize == 0) return res;
        // 初始化两个候选人candidate,和他们的计票
        int cand1 = nums[0], count1 = 0;
        int cand2 = nums[0], count2 = 0;
        int i;
        // 摩尔投票法,分为两个阶段:配对阶段和计数阶段
        // 配对阶段
        for (i=0; i<numsSize; i++) {
            // 投票
            if (cand1 == nums[i]) {
                count1++;
                continue;
            }
            if (cand2 == nums[i]) {
                count2++;
                continue;
            }
            
            // 第1个候选人配对
            if (count1 == 0) {
                cand1 = nums[i];
                count1++;
                continue;
            }
            // 第2个候选人配对
            if (count2 == 0) {
                cand2 = nums[i];
                count2++;
                continue;
            }
            
            count1--;
            count2--;
        }
        
        // 计数阶段
        // 找到了两个候选人之后,需要确定票数是否满足大于 N/3
        count1 = 0;
        count2 = 0;
        for (i=0; i<numsSize; i++) {
            if (cand1 == nums[i]) count1++;
            else if (cand2 == nums[i]) count2++;
        }
        
        if (count1 > numsSize / 3) 
            res[(*returnSize)++]=cand1;
        if (count2 > numsSize / 3)
            res[(*returnSize)++]=cand2;
        
        return res;
    }
  • 相关阅读:
    【刷题-LeetCode】165 Compare Version Numbers
    python 22 内置模块2
    python 21 内置模块
    python 20 模块,包,及开发目录规范
    python 19
    python 18 三元,生成,递推
    定时抓取数据并存入数据库
    抓取财报数据
    金币
    交换座位
  • 原文地址:https://www.cnblogs.com/ganxiang/p/14202214.html
Copyright © 2011-2022 走看看