59
59
class Solution :
60
60
def singleNumber (self , nums : List[int ]) -> List[int ]:
61
61
eor = 0
62
- for num in nums:
63
- eor ^= num
64
- # 提取最右边的 1
65
- diff = eor & (~ eor + 1 )
66
- a = 0
67
- for num in nums:
68
- if (num & diff) == 0 :
69
- a ^= num
70
- b = eor ^ a
71
- return [a, b]
62
+ for x in nums:
63
+ eor ^= x
64
+ lowbit = eor & (- eor)
65
+ ans = [0 , 0 ]
66
+ for x in nums:
67
+ if (x & lowbit) == 0 :
68
+ ans[0 ] ^= x
69
+ ans[1 ] = eor ^ ans[0 ]
70
+ return ans
72
71
```
73
72
74
73
### ** Java**
@@ -79,23 +78,84 @@ class Solution:
79
78
class Solution {
80
79
public int [] singleNumber (int [] nums ) {
81
80
int eor = 0 ;
82
- for (int num : nums) {
83
- eor ^ = num ;
81
+ for (int x : nums) {
82
+ eor ^ = x ;
84
83
}
85
- // 提取最右的 1
86
- int diff = eor & (~ eor + 1 );
87
- int a = 0 ;
88
- for (int num : nums) {
89
- if ((num & diff) == 0 ) {
90
- a ^ = num;
84
+ int lowbit = eor & (- eor);
85
+ int [] ans = new int [2 ];
86
+ for (int x : nums) {
87
+ if ((x & lowbit) == 0 ) {
88
+ ans[0 ] ^ = x;
91
89
}
92
90
}
93
- int b = eor ^ a ;
94
- return new int []{a, b} ;
91
+ ans[ 1 ] = eor ^ ans[ 0 ] ;
92
+ return ans ;
95
93
}
96
94
}
97
95
```
98
96
97
+ ### ** JavaScript**
98
+
99
+ ``` js
100
+ /**
101
+ * @param {number[]} nums
102
+ * @return {number[]}
103
+ */
104
+ var singleNumber = function (nums ) {
105
+ let eor = 0 ;
106
+ for (const x of nums) {
107
+ eor ^= x;
108
+ }
109
+ const lowbit = eor & (- eor);
110
+ let ans = [0 ];
111
+ for (const x of nums) {
112
+ if ((x & lowbit) == 0 ) {
113
+ ans[0 ] ^= x;
114
+ }
115
+ }
116
+ ans .push (eor ^ ans[0 ]);
117
+ return ans;
118
+ };
119
+ ```
120
+
121
+ ### ** C++**
122
+
123
+ ``` cpp
124
+ class Solution {
125
+ public:
126
+ vector<int > singleNumber(vector<int >& nums) {
127
+ long long eor = 0;
128
+ for (int x : nums) eor ^= x;
129
+ int lowbit = eor & (-eor);
130
+ vector<int > ans(2);
131
+ for (int x : nums)
132
+ if ((x & lowbit) == 0) ans[ 0] ^= x;
133
+ ans[ 1] = eor ^ ans[ 0] ;
134
+ return ans;
135
+ }
136
+ };
137
+ ```
138
+
139
+ ### **Go**
140
+
141
+ ```go
142
+ func singleNumber(nums []int) []int {
143
+ eor := 0
144
+ for _, x := range nums {
145
+ eor ^= x
146
+ }
147
+ lowbit := eor & (-eor)
148
+ ans := make([]int, 2)
149
+ for _, x := range nums {
150
+ if (x & lowbit) == 0 {
151
+ ans[0] ^= x
152
+ }
153
+ }
154
+ ans[1] = eor ^ ans[0]
155
+ return ans
156
+ }
157
+ ```
158
+
99
159
### ** ...**
100
160
101
161
```
0 commit comments