题目链接
leetcode
题目描述
给你一个 非空 整数数组 nums
,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
设计并实现线性时间复杂度 O(n)
的算法来解决此问题,且该算法只使用常量额外空间 O(1)
。
C++ 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| #include <iostream> #include <vector> #include <unordered_map> using namespace std;
class Solution_0 { public: int singleNumber(vector<int>& nums) { unordered_map<int, int> num2cnt; for (int num : nums) { num2cnt[num]++; }
for (const auto& [k, v] : num2cnt) { if (v == 1) { return k; } } return -1; } };
class Solution { public: int singleNumber(vector<int>& nums) { int res = 0; for (int num : nums) { res ^= num; } return res; } };
void printArray(const vector<int>& nums) { cout << "["; for (size_t i = 0; i < nums.size(); i++) { cout << nums[i]; if (i != nums.size() - 1) cout << ","; } cout << "]"; }
int main() { Solution solution; vector<vector<int>> nums_cases = { {2,2,1}, {4,1,2,1,2}, {1} }; for (auto& nums : nums_cases) { cout << "Input: nums = "; printArray(nums); cout << endl; int result = solution.singleNumber(nums); cout << "Output: " << result << endl; }
return 0; }
|