[leetcode] 229. Majority Element II
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                [leetcode] 229. Majority Element II
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.                        
                                
Given an integer array of size?n, find all elements that appear more than?? n/3 ??times. The algorithm should run in linear time and in O(1) space.
Hint:
Moore voting的方法。
class Solution { public:vector<int> majorityElement(vector<int>& nums) {vector<int> res;int m=0, n=0, cm=0, cn=0;for(auto &a:nums){if(a==m) ++cm;else if(a==n) ++cn;else if(cm==0) m=a, cm=1;else if(cn==0) n=a, cn=1;else --cm, --cn;}cm=0; cn=0;for(auto &a:nums){if(a==m) cm++;else if(a==n) cn++;}if(cm>nums.size()/3) res.push_back(m);if(cn>nums.size()/3) res.push_back(n);return res;} };
總結(jié)
以上是生活随笔為你收集整理的[leetcode] 229. Majority Element II的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 利用confluence搭建wiki
- 下一篇: python 英语分词_基于Python
