标签:style class blog code color os
题目描述:寻找发帖水王,转换一下就是:给定一个数组,找出出现次数大于n/2的元素
思路:
(1)排序,直接输出中间元素
(2)O(N),每次删除两个不同元素,注意代码实现
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 else 23 { 24 if(cur == a[i]) 25 { 26 num++; 27 } 28 else 29 { 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 }
标签:style class blog code color os
原文地址:http://www.cnblogs.com/cane/p/3809603.html