首页 > 其他 > 详细

LeetCode【169. Majority Element】

时间:2016-08-06 15:45:36      阅读:161      评论: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.

 

思路.1

排序,选择第n/2个数,调用STL的sort,所以时间复杂度是O(nlogn)

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        sort(nums.begin(),nuns.end());
        return nums[nums.size()/2];
    }
};

  

思路2>

设置一个计数,当count为0时设置majority的值,如果下一个值与majority相同则count+1,如果不同,则-1,知道count==0时,重新赋值,因为majority肯定大于n/2所以最后>0的count的肯定是majority,这样,就只需要遍历一遍就可以求出majority,时间复杂度为O(n)

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int Majority = nums[0];
        int count = 1;
        for( int i = 1; i < nums.size(); i++ ){
            if( count == 0 ){
                count++;
                Majority = nums[i];
            }
            else if( Majority == nums[i] ){
                count++;
            }
            else if ( Majority != nums[i] ){
                count--;
            }
        }
        return Majority;
    }
};

  

LeetCode【169. Majority Element】

原文:http://www.cnblogs.com/rockwall/p/5744194.html

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