Majority Element (Leet Code)

来源:互联网 发布:淘宝不能登录怎么办 编辑:程序博客网 时间:2024/05/22 11:32

Majority Element

 Total Accepted: 58215 Total Submissions: 16289

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Show Tags
Show Similar Problems

1

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


0 0
原创粉丝点击