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;
    }
  • 相关阅读:
    采样错误
    MathJax
    jupyter
    pip
    str操作
    Content-Type
    json转csv
    【tornado】静态文件
    dict 字典
    基于插件技术的GIS应用框架(C# + ArcEngine9.3)(一)
  • 原文地址:https://www.cnblogs.com/ganxiang/p/14202214.html
Copyright © 2011-2022 走看看