|
46 | 46 |
|
47 | 47 | ## Solutions
|
48 | 48 |
|
| 49 | +**Solution 1: Bitwise Operation** |
| 50 | + |
| 51 | +The XOR operation has the following properties: |
| 52 | + |
| 53 | +- Any number XOR 0 is still the original number, i.e., $x \oplus 0 = x$; |
| 54 | +- Any number XOR itself is 0, i.e., $x \oplus x = 0$; |
| 55 | + |
| 56 | +Therefore, we can traverse the array, perform XOR operation between each element and the numbers $[0,..n],ドル and the final result will be the missing number. |
| 57 | + |
| 58 | +The time complexity is $O(n),ドル where $n$ is the length of the array. The space complexity is $O(1)$. |
| 59 | + |
| 60 | +**Solution 2: Mathematics** |
| 61 | + |
| 62 | +We can also solve this problem using mathematics. By calculating the sum of $[0,..n],ドル subtracting the sum of all numbers in the array, we can obtain the missing number. |
| 63 | + |
| 64 | +The time complexity is $O(n),ドル where $n$ is the length of the array. The space complexity is $O(1)$. |
| 65 | + |
49 | 66 | <!-- tabs:start -->
|
50 | 67 |
|
51 | 68 | ### **Python3**
|
@@ -141,6 +158,58 @@ func missingNumber(nums []int) (ans int) {
|
141 | 158 | }
|
142 | 159 | ```
|
143 | 160 |
|
| 161 | +### **Rust** |
| 162 | + |
| 163 | +```rust |
| 164 | +impl Solution { |
| 165 | + pub fn missing_number(nums: Vec<i32>) -> i32 { |
| 166 | + let n = nums.len() as i32; |
| 167 | + let mut ans = n; |
| 168 | + for (i, v) in nums.iter().enumerate() { |
| 169 | + ans ^= i as i32 ^ v; |
| 170 | + } |
| 171 | + ans |
| 172 | + } |
| 173 | +} |
| 174 | +``` |
| 175 | + |
| 176 | +```rust |
| 177 | +impl Solution { |
| 178 | + pub fn missing_number(nums: Vec<i32>) -> i32 { |
| 179 | + let n = nums.len() as i32; |
| 180 | + let mut ans = n; |
| 181 | + for (i, &v) in nums.iter().enumerate() { |
| 182 | + ans += i as i32 - v; |
| 183 | + } |
| 184 | + ans |
| 185 | + } |
| 186 | +} |
| 187 | +``` |
| 188 | + |
| 189 | +### **TypeScript** |
| 190 | + |
| 191 | +```ts |
| 192 | +function missingNumber(nums: number[]): number { |
| 193 | + const n = nums.length; |
| 194 | + let ans = n; |
| 195 | + for (let i = 0; i < n; ++i) { |
| 196 | + ans ^= i ^ nums[i]; |
| 197 | + } |
| 198 | + return ans; |
| 199 | +} |
| 200 | +``` |
| 201 | + |
| 202 | +```ts |
| 203 | +function missingNumber(nums: number[]): number { |
| 204 | + const n = nums.length; |
| 205 | + let ans = n; |
| 206 | + for (let i = 0; i < n; ++i) { |
| 207 | + ans += i - nums[i]; |
| 208 | + } |
| 209 | + return ans; |
| 210 | +} |
| 211 | +``` |
| 212 | + |
144 | 213 | ### **JavaScript**
|
145 | 214 |
|
146 | 215 | ```js
|
|
0 commit comments