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.
s思路: 1. 有一个很著名的算法专门干这个的。 2. 明天思考一下,这个方法为啥行?
class Solution {public: int majorityElement(vector<int>& nums) { // int count=0; int mj=0; for(int num:nums){ if(count==0) mj=num; if(num==mj) count++; else count--; } return mj; }};新闻热点
疑难解答