广联达7.29笔试 各不相同
时间太短,代码根本写不出来😓 只能考后重新写……献上菜鸡我的代码。
题目描述:
令x为序列中最小的重复的数字,删除序列左数第一个x,把第二个x替换为2*x,输出最终序列.
例如[2 2 1 1 1] 输出[4 2 1], [5 5 5 5 4]输出[20 4], [1 2 1 2 1 1] 输出[8], [-1 -2 -1 -1]输出[-4 -1]
用了unordered_map,试了几个好像输出是对的。
#include <iostream>
#include <algorithm>
#include <vector>
#include <unordered_map>
using namespace std;
int main()
{
int n; //数组元素的个数
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++)
cin >> arr[i];
vector<pair<int,int> > res;
unordered_map<int, int> hash_map;
for (int i = 0; i < n; i++)
{
int tmp = arr[i];
auto iter = hash_map.find(tmp);
while (!hash_map.empty() && iter != hash_map.end())//hash表中存在这个元素
{
hash_map.erase(tmp);
tmp *= 2;//这个数成两倍
iter = hash_map.find(tmp);//再去寻找这个数
}
int idx = hash_map.size();
hash_map.insert({ tmp,idx });
}
for (auto iter : hash_map)
{
res.push_back(iter); //把元素和下标都放进去
}
//按照下标排序
sort(res.begin(), res.end(),
[=](std::pair<int, int>& a, std::pair<int, int>& b) { return a.second < b.second; });
for (auto iter : res)
{
cout << iter.first << " ";
}
return 0;
}
笔试只写了第一道5555