169. Majority Element

来源:互联网 发布:李医生祛痘洁面乳 知乎 编辑:程序博客网 时间:2024/06/10 17:46

问题描述:

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

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

解题思路:

首先,该题的意思是找出相同元素超过一半的元素,那么,就可以以成对的方式来进行查询,以count计量,相同count++,出现不一样的count--,最后就能找到n/2的元素。

#include "stdio.h"
int majorityElement(int *nums,int numsSize){
    int i,count=1,major=nums[0];
    for(i=1;i<numsSize;i++)
    {
        if(count==0){
            count++;
            major=nums[i];
        }
        else if(major==nums[i]) count++;
        else count--;
        printf("%d\n",major);
    }
    printf("%d\n",major);
    return major;
}
void main()
{
    int a[20]={3,4,5,2,3,4,5,3,4,3,7,3,6,7,9,0,3,8,3,2};
    majorityElement(a,20);
}



原创粉丝点击