Leetcode---Majority element

来源:互联网 发布:分布式数据库解决方案 编辑:程序博客网 时间:2024/06/07 01:27

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
在一个数组中,出现次数大于n/2次数的只可能有一个。开始时count为0,如果数组中的数和candidate相同,则加1。如果不同,则减1。

class Solution {public:    int majorityElement(vector<int>& nums) {        int candidate = 0;        int count = 0;        for(int i = 0; i < nums.size(); i ++)        {            if(count == 0)            {                candidate = nums[i];                count = 1;            }            else            {                if(nums[i] == candidate)                    count ++;                else                    count --;            }        }        return candidate;    }};
0 0
原创粉丝点击