数组中只出现一次的两个数字_牛客题霸_牛客网 (nowcoder.com)
1. 可以用哈希表来做
- 时间复杂度:O(n),其中n为数组长度,两次单独的遍历数组每个元素
- 空间复杂度:O(n),哈希表的长度应该为(n−2)/2
class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param array int整型vector * @return int整型vector */ vector<int> FindNumsAppearOnce(vector<int>& array) { // write code here unordered_map<int,int> mp; vector<int> res; int n = array.size(); for(int i = 0; i < n; ++i){ mp[array[i]]++; } for(int i = 0; i < n; ++i){ if(mp[array[i]] == 1) res.push_back(array[i]); } if(res[0] > res[1]) return {res[1],res[0]}; else return {res[0],res[1]}; } };