码迷,mamicode.com
首页 > 其他好文 > 详细

数众数

时间:2016-01-21 23:10:51      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:

有序整数序列,数出所有众数及其个数

模块1:线性扫描

模块2:cnt计数:条件:遇见不等,计a[i-1]的cnt

 

notice: 最后一个数一定不会入栈,需要单独处理

 1 #include <iostream>
 2 #include <vector>
 3 #include <stack>
 4 using namespace std;
 5 void findMode(vector<int> &a, stack<int> &x, stack<int> &y){
 6     int cnt = 1;
 7     y.push(-1);
 8     for (int i = 1; i < a.size(); i++){
 9         if  (a[i] == a[i-1])
10             cnt++;
11         else{
12             if (cnt == y.top()){
13                 x.push(a[i-1]);
14                 y.push(cnt);
15             }
16             else if (cnt > y.top()){
17                 while( !x.empty() )
18                     x.pop();
19                 while( !y.empty() )
20                     y.pop();
21                 x.push(a[i-1]);
22                 y.push(cnt);
23             }
24             cnt = 1;
25         }
26     }
27     if (cnt == y.top()){
28         x.push(a[a.size()-1]);
29         y.push(cnt);
30     }
31     else if (cnt > y.top()){
32         while( !x.empty() )
33             x.pop();
34         while( !y.empty() )
35             y.pop();
36         x.push(a[a.size()-1]);
37         y.push(cnt);
38     }
39 }
40 int main(){
41     vector<int> a;
42     stack<int> x, y;
43     a.push_back(1);
44     a.push_back(2);
45     a.push_back(3);
46     findMode(a, x, y);
47     while( !x.empty() || !y.empty() ){
48         cout << x.top() << " " << y.top() << endl;
49         x.pop();
50         y.pop();
51     }
52     return 0;
53 }

 

数众数

标签:

原文地址:http://www.cnblogs.com/celahir/p/5149280.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!