-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsingleNumber.go
More file actions
43 lines (34 loc) · 1002 Bytes
/
Copy pathsingleNumber.go
File metadata and controls
43 lines (34 loc) · 1002 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* https://leetcode.com/problems/single-number/#/description
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?
https://discuss.leetcode.com/topic/22068/easy-java-solution-tell-you-why-using-bitwise-xor
We use bitwise XOR to solve this problem :
first , we have to know the bitwise XOR:
0 ^ N = N
N ^ N = 0
So..... if N is the single number
N1 ^ N1 ^ N2 ^ N2 ^..............^ Nx ^ Nx ^ N
= (N1^N1) ^ (N2^N2) ^..............^ (Nx^Nx) ^ N
= 0 ^ 0 ^ ..........^ 0 ^ N
= N
*/
package lbm
func singleNumber(nums []int) int {
/* maps := make(map[int]int)
for i := 0; i < len(nums); i++ {
maps[nums[i]] += 1
}
for k, v := range maps {
if v == 1 {
return k
}
}
panic("input is error: not every element appears twice except for one")
*/
r := 0
for i := 0; i < len(nums); i++ {
r ^= nums[i]
}
return r
}