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

Majority Element

时间:2015-04-10 21:41:48      阅读:128      评论: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.

 

Solution1:

 1 int majorityElement(vector<int> &num) {
 2         int len = num.size();
 3         for(int i = 0; i <= len / 2; i++){
 4             for(int j = i + 1; j < len - i; j++){
 5                 if(num[j] < num[i]){
 6                     int temp = num[i]; 
 7                     num[i] = num[j];
 8                     num[j] = num[i];
 9                 }
10             }
11         }
12         return num[len/2];
13     }

结果超时..参照https://leetcode.com/discuss/19151/solution-computation-space-problem-can-extended-situation解题思路,可得代码如下

 

Solution2:

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

 

Majority Element

标签:

原文地址:http://www.cnblogs.com/amazingzoe/p/4415582.html

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