Description: Search for the poster, and convert it to an array to find the elements that appear more than n/2.
Ideas:
(1) sort and directly output intermediate Elements
(2) O (n): delete two different elements each time. Pay attention to the code implementation.
1 #include <iostream> 2 #include <queue> 3 #include <climits> 4 #include <algorithm> 5 #include <memory.h> 6 #include <stdio.h> 7 using namespace std; 8 9 int fun(vector<int> a)10 {11 if(a.size() == 0)12 return 0;13 int num = 0;14 int cur = a[0];15 for(int i = 1 ; i < a.size() ; ++i)16 {17 if(num == 0)18 {19 cur = a[i];20 num = 1;21 }22 else23 {24 if(cur == a[i])25 {26 num++;27 }28 else29 {30 num--;31 }32 }33 }34 return cur;35 }36 37 int main()38 {39 vector<int> a;40 a.push_back(1);41 a.push_back(2);42 a.push_back(3);43 a.push_back(2);44 a.push_back(2);45 cout<<fun(a)<<endl;46 return 0;47 }