408最优解 空间复杂度O(1)
#include <iostream>
using namespace std;
int main() {
long long temp,major=-1;
int m,n,cnt=0;
cin>>m>>n;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>temp;
if(temp!=major){
cnt--;
if(cnt<=0){
major=temp;
cnt=1;
}
}else cnt++;
}
}
cout<<major;
return 0;
}
STL中map的应⽤~使⽤arr[i] = j表示i元素在矩阵中出现了j次,在输⼊的同时⽐较arr当前的值
是否已经超过半数,如果超过,就直接输出该数字并退出程序
#include <iostream>
#include <map>
using namespace std;
int main() {
int m, n;
scanf("%d %d", &m, &n);
map<int, int> arr;
int half = m * n / 2;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
int temp;
scanf("%d", &temp);
arr[temp]++;
if(arr[temp] > half) {
printf("%d", temp);
return 0;
}
}
}
return 0;
}