题目:Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
思路:
任何数字和0异或都是数字本身,相同为0,不同为1。所以相互异或之后,最后剩余的数字就是那个仅仅出现了一次的数据。
代码:
class Solution { public: int singleNumber(vector<int>& nums) { //任何数字和本身异或的结果为0。0和某数字的异或结果为其本身。所以数组中所有数字异或结果就是所求结果。 int res=0; for(int i=0;i<nums.size();i++){ res^=nums[i]; } return res; } };