[LeetCode] Single Number III

260. Single Number III

Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.

You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
vector<int> singleNumber(vector<int>& nums) {
unordered_set<int> s;
for(auto n : nums) {
if(!s.count(n)) s.insert(n);
else s.erase(n);
}
return vector<int>(s.begin(),s.end());
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/19/PS/LeetCode/single-number-iii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.