# LeetCode Problem 169: Majority Element查找多数元素

 1 class Solution {
2 public:
3     int majorityElement(vector<int> &num) {
4
5         int elem = 0;
6         int count = 0;
7
8         for(int i = 0; i < num.size(); i++)  {
9
10             if(count == 0)  {
11                 elem = num[i];
12                 count = 1;
13             }
14             else    {
15                 if(elem == num[i])
16                     count++;
17                 else
18                     count--;
19             }
20
21         }
22         return elem;
23     }　　};

 1 class Solution {
2 public:
3     int majorityElement(vector<int> &num) {
4
5         int count = 0;
6
7         for(;;) {
8             if(num.size() == 1)
9                 return num[0];
10             else    {
11                 int i = rand() % (num.size() - 1);
12                 for(int j = 0; j < num.size(); j++) {
13                     if(num[j] == num[i])
14                         count++;
15                 }
16                 if(count > (num.size() / 2))
17                     return num[i];
18                 else    {
19                     count = 0;
20                     continue;
21                 }
22             }
23         }
24     }　　};

posted @ 2014-12-22 21:13  博临天下  阅读(10863)  评论(1编辑  收藏  举报