剑指Offer27 数组中超过一半的数

 1 /*************************************************************************
 2     > File Name: 27_MoreThanHalfNum.c
 3     > Author: Juntaran
 4     > Mail: JuntaranMail@gmail.com
 5     > Created Time: 2016年08月31日 星期三 16时40分55秒
 6  ************************************************************************/
 7 
 8 #include <stdio.h>
 9 
10 int FindNum(int* nums, int length)
11 {
12     if (nums==NULL || length<=0)
13         return -1;
14     
15     int ret = nums[0];
16     int count = 1;
17     for (int i = 0; i < length; ++i)
18     {
19         if (nums[i] == ret)
20             count ++;
21         else
22             count --;
23         if (count == 0)
24         {
25             ret = nums[i];
26             count = 1;
27         }
28     }
29     
30     // 检验是否正确
31     int count2 = 0;
32     for (int i = 0; i < length; ++i)
33     {
34         if (nums[i] == ret)
35             count2 ++;
36     }
37     if (count2*2 > length)
38         return ret;
39     else
40         return -1;
41 }
42 
43 int main()
44 {
45     int nums[] = {1,2,3,2,2,2,5,4,2};
46     int length = 9;
47     int ret = FindNum(nums, length);
48     if (ret == -1)
49         printf("Not Find\n");
50     else
51         printf("ret is %d\n", ret);
52     
53     return 0;
54 }

 

posted @ 2016-08-31 16:52  Juntaran  阅读(129)  评论(0编辑  收藏  举报