-
Notifications
You must be signed in to change notification settings - Fork 0
/
search-insert-position.rs
46 lines (40 loc) · 1.25 KB
/
search-insert-position.rs
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
#![allow(unused)]
use std::usize;
struct Solution;
/// https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
impl Solution {
pub fn impl_1(nums: Vec<i32>, target: i32) -> i32 {
for (i, v) in nums.iter().enumerate() {
if target <= *v {
return i as i32;
}
}
nums.len() as i32
}
pub fn impl_2(nums: Vec<i32>, target: i32) -> i32 {
nums.binary_search(&target).unwrap_or_else(|x| x) as i32
}
pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 {
// Solution::impl_1(nums, target)
Solution::impl_2(nums, target)
}
}
fn main() {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn impl_1() {
assert_eq!(Solution::impl_1(vec![1, 3, 5, 6], 5), 2);
assert_eq!(Solution::impl_1(vec![1, 3, 5, 6], 2), 1);
assert_eq!(Solution::impl_1(vec![1, 3, 5, 6], 7), 4);
assert_eq!(Solution::impl_1(vec![1, 3, 5, 6], 0), 0);
}
#[test]
fn impl_2() {
assert_eq!(Solution::impl_2(vec![1, 3, 5, 6], 5), 2);
assert_eq!(Solution::impl_2(vec![1, 3, 5, 6], 2), 1);
assert_eq!(Solution::impl_2(vec![1, 3, 5, 6], 7), 4);
assert_eq!(Solution::impl_2(vec![1, 3, 5, 6], 0), 0);
}
}