LeetCode136--神奇的异或

172 阅读1分钟

题目内容

  LeetCode 136: Given a non-empty array of integers, every element appears twice except for one. Find that single one. Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

Example 1:

Input: [2,2,1] Output: 1

Example 2:

Input: [4,1,2,1,2] Output: 4

解决思路

  看到题目后的第一反应是散列,但经过研究后发现这种方法不可行。标准答案的方法是使用异或运算。异或运算的规则是:将两个数按照二进制位对其后,相同为1,不同为0。例如:6^5=3。异或有两个重要性质:

  • a^a=0 0^a=a
  • a^b=b^a

  采用异或运算可以轻松解决上述题目,代码如下:

int singleNumber(vector<int>& nums) {
	int size = (int)nums.size();
	int num = nums[0];
	for (int i = 1; i < size; i++){
		num ^= nums[i];
	}
	return num;
}