zoukankan      html  css  js  c++  java
  • LeetCode 169. Majority Element

    Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

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

     利用了主元素大于一半的条件。每次从数组中取出元素,如果和暂存数组中的数相同就存进暂存数组,不同的话就“两个抵消”,最后剩下的一定是主元素

    int majorityElement(int* nums, int numsSize) 
    {
        
        int majorityElement=0;
        int *TmpArray;
        int j=-1;
        TmpArray = malloc(sizeof(int)*numsSize);
        for (int i=0; i<numsSize; i++)
        {
            if (j==-1)
            {
                TmpArray[++j] = nums[i];
            }else if (nums[i] == TmpArray[j])
            {
                TmpArray[++j] = nums[i];
            }else if (nums[i] != TmpArray[j])
            {
                    TmpArray[j--] = -1;
            }
        }
        majorityElement = TmpArray[0];
        return majorityElement;
    
    }
  • 相关阅读:
    nuc970连接jlink进行单步调试的设置
    alsa utils工具使用
    用arm-linux-gcc v4.3.4交叉编译Qt4.8.3
    LNMP分离式部署
    MHA(下)
    MHA(上)
    PXE自动装机
    JumpServer
    FTP
    DNS
  • 原文地址:https://www.cnblogs.com/evansyang/p/5442847.html
Copyright © 2011-2022 走看看