码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 169

时间:2016-05-10 20:30:55      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

 1 /*************************************************************************
 2     > File Name: LeetCode169.c
 3     > Author: Juntaran
 4     > Mail: Jacinthmail@gmail.com
 5     > Created Time: Tue 10 May 2016 02:40:25 PM CST
 6  ************************************************************************/
 7  
 8 /*************************************************************************
 9 
10     Majority Element
11     
12     Given an array of size n, find the majority element. 
13     The majority element is the element that appears more than ⌊ n/2 ⌋ times.
14 
15     You may assume that the array is non-empty and the majority element always exist in the array.
16 
17  ************************************************************************/
18 
19 #include<stdio.h>
20 
21 int majorityElement( int* nums, int numsSize )
22 {
23     int ret = nums[0];
24     int count = 1;
25     
26     int i;
27     for( i=1; i<numsSize; i++ )
28     {
29         if( ret == nums[i] )
30         {
31             count ++;
32         }
33         else
34         {
35             count --;
36         }
37         if( count == 0 )
38         {
39             ret = nums[i];
40             count ++;
41         }
42     }
43     return ret;
44 }
45 
46 int main()
47 {
48     int nums[] = {3,2,3};
49     int numsSize = 3;
50 
51     int ret = majorityElement( nums, numsSize );
52     printf("%d\n", ret);
53 
54     return 0;
55 }

 

LeetCode 169

标签:

原文地址:http://www.cnblogs.com/Juntaran/p/5479091.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!