Leetcode:Majority Element

来源:互联网 发布:java写网络扫描器 编辑:程序博客网 时间:2024/06/05 23:51

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.

因为Majority Element出现的次数超过一半,所以只要将数组排序,排序后再数组中间的那个数就是Majority Element。

实现代码:

class Solution {public:    int majorityElement(vector<int> &num) {        sort(num.begin(),num.end());        int n=num.size();        return num[n/2];    }};
上面代码的复杂度取决于排序。这里还有一种更好的方法,只需要遍历数组一遍,复杂度为O(n)。

class Solution {public:    int majorityElement(vector<int> &num) {        int vote = num[0];        int count = 1;        int size = num.size();            //vote from the second number        for( int i = 1; i < size; i++ )        {            if( count == 0 ) { vote = num[i]; count++; }            else if( vote == num[i] )   count++;            else count--;        }    return vote;    }};



0 0
原创粉丝点击