LeetCode Majority Element (c++)

来源:互联网 发布:多级审批数据库设计 编辑:程序博客网 时间:2024/05/19 19:41

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.


class Solution {public:    int majorityElement(vector<int> &num) {        //   int n = num.size();                    注释的这三行也是一种solution,不过时间要翻翻,原因主要在于sort()方法        // sort(num.begin(),num.end());          // return num[n/2];         int nTimes = 0;        int candidate = 0;        for(int i = 0; i < num.size(); i ++)        {            if(nTimes == 0)            {                candidate = num[i];                nTimes = 1;            }            else            {                if(candidate == num[i])                    nTimes ++;                else                    nTimes --;            }        }        return candidate;    }};


0 0