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

[LeetCode]Majority Element

时间:2015-01-06 22:55:36      阅读:206      评论: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.

 

解答:题目是要求一个数组中出现次数最多的元素,该元素的出现次数超过n/2.思路如下:将该数组进行排序,出现次数大于n/2的数字必在中间,即求解。

为了简化,可以考虑有些数组已经是排好序的了,在进行冒泡排序法的过程中,如果检验相邻的两个元素相等,则进行累加计数,一次遍历之后统计该计数值和n/2的关系,大于则为要求元素。

代码如下:

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

 

[LeetCode]Majority Element

标签:

原文地址:http://www.cnblogs.com/jamweak/p/4207114.html

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