MarsCode刷题--找单独的数
题目描述
问题描述
有一堆数字,除了一个数字,其它的数字都是成对出现。班上的每个同学拿一个数字,正好将这些数字全部拿完,问如何快速找到拿了单独数字的同学?
输入格式
- 空格分隔输入所有的数字
输出格式
- 单独的那个数字
输入样例(1)
1 1 2 2 3 3 4 5 5
输出样例(1)
4
输入样例(2)
0 1 0 1 2
输出样例(2)
2
算法分析
使用哈希表或者位运算
完整代码
#include <iostream>
#include <vector>
#include<unordered_map>
using namespace std;
int solution(std::vector<int> inp) {// Edit your code hereunordered_map<int,int>m;for(auto i:inp){m[i]++;}for(auto kv:m){if(kv.second==1)return kv.first;}return 0;
}int main() {// Add your test cases herestd::cout << (solution({1, 1, 2, 2, 3, 3, 4, 5, 5}) == 4) << std::endl;std::cout << (solution({0, 1, 0, 1, 2}) == 2) << std::endl;return 0;
}