Asked 3 months ago
0Comments
1 Views
Given a non-empty array of integers, every element appears twice except for one. Find that single element.
Approach 1: Brute Force
class Solution {
public:
int singleNumber(vector<int>& nums) {
int num = 0;
for (int i = 0; i < nums.size(); i++) {
bool found = false;
for (int j = 0; j < nums.size(); j++) {
if (i != j && nums[i] == nums[j]) {
found = true;
break;
}
}
if (!found) {
num = nums[i];
break;
}
}
return num;
}
};
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_map<int, int> hashTable;
for (int num : nums) {
hashTable[num]++;
}
for (auto& pair : hashTable) {
if (pair.second == 1) {
return pair.first;
}
}
return -1; // Should not reach here
}
};
Explanation:
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_map<int, int> hashTable;
for (int num : nums) {
hashTable[num]++;
}
for (auto& pair : hashTable) {
if (pair.second == 1) {
return pair.first;
}
}
return -1; // Should not reach here
}
};
ans
to 0.ans
.a ^ a = 0
(self-inverse)a ^ 0 = a
(identity)a ^ b = b ^ a
(commutative)(a ^ b) ^ c = a ^ (b ^ c)
(associative)Share