首页 > 学院 > 开发设计 > 正文

LeetCode作业Majority Element

2019-11-06 07:34:27
字体:
来源:转载
供稿:网友
题目原址:点击打开链接题目描述:

Given an array of size n, find the majority element. The majority element is the element that appearsmore 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 elem = 0;        int count = 0;                for(int i = 0; i < num.size(); i++)  {                        if(count == 0)  {                elem = num[i];                count = 1;            }            else    {                if(elem == num[i])                    count++;                else                    count--;            }                    }        return elem;    }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表