-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathSingleNumber.java
84 lines (56 loc) · 1.56 KB
/
SingleNumber.java
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
Source : https://leetcode.com/problems/single-number/
Time: O(n), where n is the size of the given array(nums)
Space: O(1), in-place
*/
class Solution {
public int singleNumber(int[] nums) {
int singleNumber = nums[0];
int len = nums.length;
for(int i = 1; i < len; ++i) {
singleNumber ^= nums[i];
}
return singleNumber;
}
}
/*
You might be wondering why it works?
Suppose, nums[] = {5, 6, 3, 2, 6, 2, 5}
Here, only 3 is the single element
For better undestanding, group same values together and applying bitwise XOR operator(^) on them
eg:
((5 ^ 5) ^ (6 ^ 6) ^ (2 ^ 2) ^ 3)
(0 ^ 0 ^ 0 ^ 3) --> (0 ^ 3) --> 3
What XOR property says?
1 ^ 1 = 0, so (5 ^ 5) = 0, (6 ^ 6) = 0 and (2 ^ 2) = 0
0 ^ 1 = 1, so (0 ^ 3) = 3
*/
---------------------------------------------------------------------------------------------------
/*
2nd approach using a single variable
Time: O(n), where n is the size of the given array(nums)
Space: O(1), in-place
*/
class Solution {
public int singleNumber(int[] nums) {
int singleNumber = nums[0];
for(int i = nums.length - 1; i > 0; --i) {
singleNumber ^= nums[i];
}
return singleNumber;
}
}
---------------------------------------------------------------------------------------------------
/*
3rd approach without using any extra variable
Time: O(n), where n is the size of the given array(nums)
Space: O(1), in-place
*/
class Solution {
public int singleNumber(int[] nums) {
for(int i = nums.length - 1; i > 0; --i) {
nums[0] ^= nums[i];
}
return nums[0];
}
}