您的位置:首页 > 其它

LeetCode 169

2016-05-10 19:08 225 查看
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.

/*************************************************************************
> File Name: LeetCode169.c
> Author: Juntaran
> Mail: Jacinthmail@gmail.com
> Created Time: Tue 10 May 2016 02:40:25 PM CST
************************************************************************/

/*************************************************************************

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.

************************************************************************/

#include<stdio.h>

int majorityElement( int* nums, int numsSize )
{
int ret = nums[0];
int count = 1;

int i;
for( i=1; i<numsSize; i++ )
{
if( ret == nums[i] )
{
count ++;
}
else
{
count --;
}
if( count == 0 )
{
ret = nums[i];
count ++;
}
}
return ret;
}

int main()
{
int nums[] = {3,2,3};
int numsSize = 3;

int ret = majorityElement( nums, numsSize );
printf("%d\n", ret);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: