136. 只出现一次的数字

Introduction

Question:136. 只出现一次的数字

Analysis

比较简单的题目。可以用 HashMap 来做,但是空间复杂度就为O(n)了。

这道题只需要利用异或操作的一些特性就好了:

  • A ^ A = 0
  • A ^ B ^ A = B

所以我们只需要遍历一次数组,对所有元素进行异或,最后得到的值即为只出现一次的数字。

Implement

1
2
3
4
5
int singleNumber(vector<int>& nums) {
int res = 0;
for(auto &i: nums) res ^= i;
return res;
}

One More Thing