-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy path0268_missing_number.rs
More file actions
63 lines (56 loc) 路 1.34 KB
/
Copy path0268_missing_number.rs
File metadata and controls
63 lines (56 loc) 路 1.34 KB
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
//! Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
//!
//! Example 1:
//! ```
//! Input: [3,0,1]
//! Output: 2
//! ```
//!
//! Example 2:
//! ```
//! Input: [9,6,4,2,3,5,7,0,1]
//! Output: 8
//! ```
//!
//! Note:
//! Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
//!
struct Solution;
impl Solution {
pub fn missing_number(nums: Vec<i32>) -> i32 {
let len = (nums.len() + 1) as i32;
let sum: i32 = nums.iter().sum();
match len {
1..=2 => { // not a good idea but works
len - 1 - sum
}
3 => {
len - sum
}
_ => {
let s = if len % 2 == 0 {
(len - 1) * (len / 2)
} else {
len * (len - 1)
};
s - sum
}
}
}
}
#[cfg(test)]
mod tests {
use super::Solution;
#[test]
fn test_0() {
assert_eq!(Solution::missing_number(vec![3, 0, 1]), 2);
}
#[test]
fn test_1() {
assert_eq!(Solution::missing_number(vec![9, 6, 4, 2, 3, 5, 7, 0, 1]), 8);
}
#[test]
fn test_2() {
assert_eq!(Solution::missing_number(vec![1]), 0);
}
}