136. Single Number
题目
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?
题目大意
短小精悍的一道题,给定一个数组,每个元素都出现了两次,但是有一个只出现了一次,求出是哪一个元素?线性复杂度,常数空间.
代码
1 | class Solution { |
解答
使用位运算, XOR异或.
XOR will return 1 only on two different bits. So if two numbers are the same, XOR will return 0. Finally only one number left.
A ^ A = 0 and A ^ B ^ A = B.
Author: corn1ng
Link: https://corn1ng.github.io/2018/01/02/算法/leetcode136/
License: 知识共享署名-非商业性使用 4.0 国际许可协议