原题网址:http://www.lintcode.com/zh-cn/problem/majority-number/
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。
注意事项
You may assume that the array is non-empty and the majority number always exist in the array.
标签
1 #include <iostream>
2 #include <vector>
3 #include <math.h>
4 using namespace std;
5
6
7
8 int majorityNumber(vector<int> &nums) //主元素;
9 {
10 int size=nums.size();
11
12 int count=0; //计数器;
13 int temp;
14
15 for (int i=0;i<size;i++)
16 {
17 if (count==0)
18 {
19 temp=nums[i];
20 }
21 if (temp==nums[i])
22 {
23 count++;
24 }
25 else
26 {
27 count--;
28 }
29 }
30 return temp;
31 }
32
33
34 /*vector<int> num;
35 num.push_back(nums[0]);
36
37 bool notSame=true;
38 for (int i=1;i<size;i++)
39 {
40 for (int j=0;j<(int)num.size();j++)
41 {
42 if (num[j]==nums[i])
43 {
44 notSame=false;
45 break;
46 }
47 }
48 if (notSame)
49 {
50 num.push_back(nums[i]);
51 }
52 }
53
54 int count=0;
55
56 for (int m=0;m<(int)num.size();m++)
57 {
58 for (int k=0;k<size;k++)
59 {
60 if (num[m]==nums[k])
61 {
62 count++;
63 }
64 }
65 if (count>(size/2))
66 {
67 return num[m];
68 }
69 } */
70
参考:
1 https://www.jianshu.com/p/73625dd9ac65
2 https://blog.csdn.net/whhg001/article/details/51174226
3 https://blog.csdn.net/guoziqing506/article/details/51434299
4 https://blog.csdn.net/lyy_hit/article/details/49512147