算法-优化:以空间换时间
找n个小写字母中出现次数最多的字母
#include <iostream>
#include <vector>
using namespace std;
//给出n个字母(小写字母从a到z),找出出现次数最多的字母并输出该字母
//方法一:枚举法,使用两次for循环
void method(vector<char>& chars){
int n = chars.size();
int result;//记录下标
int maxCount = 0;//记录最多的出现次数
for(int i = 0; i < n; i++){
int count = 0;
for(int j = 0; j < n; j++){
if(chars[i] == chars[j]){
count++;
}
}
if(maxCount < count){
maxCount = count;
result = i;
}
}
cout<<"出现次数最多的字符是:"<<chars[result]<<endl;
}
int main(){
vector<char> chars = {'a','b','c','d','e','a','b','a','c'};
method(chars);
return 0;
}
采用以空间换时间来优化函数,哈希法(数组、set、map等容器)也是基于此思想实现的,哈希法的时间复杂度可以达到O(1)。
#include <iostream>
#include <vector>
using namespace std;
//给出n个字母(小写字母从a到z),找出出现次数最多的字母并输出该字母
//方法二:新建一个数组用来保存每个字符的出现次数,数组最大占用26个字符
//使用ASCII数值计算,只需遍历一次数组
void method(vector<char>& chars){
int n = chars.size();
int num[26]={0};
for(int i = 0; i < n; i++){
num[chars[i]-'a']++;
}
int maxCount = 0;//记录最多的出现次数
int result;
for(int i = 0; i < 26; i++){
if(maxCount < num[i]){
maxCount = num[i];
result = i;
}
}
cout<<"出现次数最多的字符是:"<<chars[result]<<endl;
}
int main(){
vector<char> chars = {'a','b','c','d','e','a','b','a','c'};
method(chars);
return 0;
}