136. Single Number
Given a non-empty 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?
Example 1:
1 | Input: [2,2,1] |
Example 2:
1 | Input: [4,1,2,1,2] |
Method1: 排序
分析:要求Run time O(N), Space Complexity: O(1)
==> 考虑Sort the array
Note: Step = 2时,要考虑最后一个数是否可取,确认范围
1 | class Solution: |
Methos2:Bit Manipulation(XOR)
分析:
- $a ⊕ 0 = a$
- $a ⊕ a = 0$
- $a ⊕ b ⊕ a = (a ⊕ a) ⊕ b = 0 ⊕ b = b$
计算nums里面每一个num ⊕ 运算的结果,最后的值就是the Single number
1 | def singleNumber2(self, nums): |