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

LeeCode-Majority Element

时间:2015-07-20 10:29:23      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:

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 int majorityElement(int* nums, int numsSize) 
 2 {
 3     if(numsSize==1)
 4         return nums[0];
 5     
 6     
 7     int i,j,k;
 8     for(i=1;i<numsSize;i++)
 9     {
10         for(j=i-1;j>=0;j--)
11         {
12             if(nums[i]>=nums[j])
13                 break;
14         }
15 
16         if(i!=j-1)
17         {
18             int temp=nums[i];
19             for(k=i-1;k>j;k--)
20             {
21                 nums[k+1]=nums[k];
22             }
23             nums[k+1]=temp;
24         }
25     }
26 
27     int Time;
28     Time=numsSize/2;
29     int count=1;
30     for(i=0;i<numsSize-1;i++)
31     {
32         if(nums[i]==nums[i+1])
33         {
34             count++;
35             if(count>Time)
36             {
37                 return nums[i];
38             }
39         }
40         else
41         {
42             count=1;
43         }
44     }
45     
46 
47     return 0;
48 }

 

LeeCode-Majority Element

标签:

原文地址:http://www.cnblogs.com/vpoet/p/4660492.html

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