首页 > 其他 > 详细

Majority Element--LeetCode

时间:2015-04-12 10:42:45      阅读:95      评论: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之后的元素相等,说明就是这个元素。

#include <iostream>
#include <vector>
using namespace std;

int majorityElement(vector<int> &num) 
{
    int i,j;
    int key = num[0];
    for(i=-1,j=0;j<num.size();j++)
    {
        if(num[j]<key)
        {
           i++;
           swap(num[i],num[j]);
        }                              
    } 
    
    for(i=0;i<num.size()/2;i++)
    {
        key = num[i+num.size()/2];
        if(num[i] == key)
         return key;                        
    }       
}

int main()
{
    int array[]={3,2,4,5,2,2,4,2,2,2,2,7};
    vector<int> vec(array,array+sizeof(array)/sizeof(int));
    cout<<majorityElement(vec);
    system("pause");
    return 0;
    }


Majority Element--LeetCode

原文:http://blog.csdn.net/yusiguyuan/article/details/45007583

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!