229. Majority Element II

来源:互联网 发布:淘宝女装卫衣 编辑:程序博客网 时间:2024/06/07 00:58

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.

Subscribe to see which companies asked this question

其实为我不太清楚这个流程,但是写法感觉比较优美:
class Solution {public:    vector<int> majorityElement(vector<int>& nums) {       if(nums.size()<2) return nums;       vector<int> ans;       int a = 0;       int a_1=0;       int b =0;       int b_1=0;             for( int i=0;i<nums.size();++i)       {           if(nums[i]==a)            {               a_1++;           }           else if(nums[i]==b)            {               b_1++;           }                      else if(a_1==0)           {              a=nums[i];              a_1=1;           }           else if(b_1==0)           {               b=nums[i];               b_1=1;           }           else           {               a_1--;               b_1--;           }       }       int c_1,c_2;       c_1=0;c_2=0;       for(int i=0;i<nums.size();++i)       {           if(nums[i]==a) c_1++;           if(nums[i]==b) c_2++;       }       if(c_1>(nums.size()/3)) ans.push_back(a);       if(a!=b && c_2>(nums.size()/3)) ans.push_back(b);       return ans;    }};


0 0
原创粉丝点击