首页 > 其他 > 详细

LeetCode 169

时间:2016-05-10 20:30:34      阅读:224      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!