- Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patha0035_search_insert_position.rs
83 lines (66 loc) · 1.64 KB
/
a0035_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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
* [0035] search-insert-position
*/
pubstructSolution{}
// solution impl starts here
implSolution{
pubfnsearch_insert(nums:Vec<i32>,target:i32) -> i32{
letmut low:i32 = 0;
letmut high:i32 = nums.len()asi32 - 1;
letmut mid;
while low < high {
mid = (low + high) / 2;
if nums[mid asusize] == target {
return mid;
}
if nums[mid asusize] < target {
low = mid + 1;
}else{
high = mid - 1;
}
}
if target <= nums[low asusize]{
return low asi32;
}
low + 1
}
}
// solution impl ends here
// solution tests starts here
#[cfg(test)]
mod tests {
usesuper::*;
#[test]
fntest_case0(){
assert_eq!(Solution::search_insert(vec![1,3,5,6],5),2);
}
#[test]
fntest_case1(){
assert_eq!(Solution::search_insert(vec![1,3,5,6],2),1);
}
#[test]
fntest_case2(){
assert_eq!(Solution::search_insert(vec![1,3,5,6],7),4);
}
#[test]
fntest_case3(){
assert_eq!(Solution::search_insert(vec![1,3,5,6],0),0);
}
#[test]
fntest_case4(){
assert_eq!(Solution::search_insert(vec![1,3],0),0);
}
#[test]
fntest_case5(){
assert_eq!(Solution::search_insert(vec![1,3],1),0);
}
#[test]
fntest_case6(){
assert_eq!(Solution::search_insert(vec![1],1),0);
}
#[test]
fntest_case7(){
assert_eq!(Solution::search_insert(vec![1,3],2),1);
}
}
// solution tests ends here