Skip to content

Commit 45b431d

Browse files
committed
Solve #268
1 parent 7506e4d commit 45b431d

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -210,3 +210,4 @@ mod n0258_add_digits;
210210
mod n0260_single_number_iii;
211211
mod n0263_ugly_number;
212212
mod n0264_ugly_number_ii;
213+
mod n0268_missing_number;

src/n0268_missing_number.rs

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* [268] Missing Number
3+
*
4+
* Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
5+
*
6+
* Example 1:
7+
*
8+
*
9+
* Input: [3,0,1]
10+
* Output: 2
11+
*
12+
*
13+
* Example 2:
14+
*
15+
*
16+
* Input: [9,6,4,2,3,5,7,0,1]
17+
* Output: 8
18+
*
19+
*
20+
* Note:<br />
21+
* Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
22+
*/
23+
pub struct Solution {}
24+
25+
// submission codes start here
26+
27+
impl Solution {
28+
pub fn missing_number(nums: Vec<i32>) -> i32 {
29+
((nums.len() + 1) * nums.len()) as i32 / 2 - nums.into_iter().fold(0, |acc, v| { acc + v })
30+
}
31+
}
32+
33+
// submission codes end
34+
35+
#[cfg(test)]
36+
mod tests {
37+
use super::*;
38+
39+
#[test]
40+
fn test_268() {
41+
assert_eq!(Solution::missing_number(vec![3,0,1]), 2);
42+
}
43+
}

0 commit comments

Comments
 (0)