missing number solution added

This commit is contained in:
Luca Lombardo
2023-09-28 15:59:54 +02:00
parent c8c16c450d
commit a6459fff7c
5 changed files with 50 additions and 1 deletions
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "missing_number"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
+24
View File
@@ -0,0 +1,24 @@
# Comments on the solution
We are using a simple mathematical approach that it's pretty much self-explanatory. We can express the sum of all numbers from `0` to `n` as `n * (n + 1) / 2`. We can then subtract the sum of the array from the sum of all numbers from `0` to `n` to get the missing number.
### Complexity
- **Time Complexity:** `O(n)` - We are iterating over the array once.
- **Space Complexity:** `O(1)` - We are not using any extra space.
---
### Solution in Rust
```rust
fn missing_number(nums: Vec<i32>) -> i32 {
(1..=nums.len() as i32).sum::<i32>() - nums.iter().sum::<i32>()
}
```
where we use the `..=` range operator to create a range from `1` to the length of the input vector, and then sum the values in that range using the `sum` method
### Leetcode result
![](https://i.imgur.com/qW2tNVm.png)
+10
View File
@@ -0,0 +1,10 @@
// Given an array nums containing n distinct numbers in the range [0, n], return the only number in the range that is missing from the array.
fn missing_number(nums: Vec<i32>) -> i32 {
(1..=nums.len() as i32).sum::<i32>() - nums.iter().sum::<i32>()
}
fn main() {
let nums = vec![3, 0, 1];
println!("{}", missing_number(nums));
}