Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c6b8ec1

Browse files
committed
q704
1 parent 2a9d0c5 commit c6b8ec1

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

‎array/src/q704.rs

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
2+
struct Solution ();
3+
impl Solution {
4+
pub fn search(nums: Vec<i32>, target: i32) -> i32 {
5+
6+
match nums.len() {
7+
0 => -1,
8+
1 => if nums[0] == target { 0 } else { -1 }
9+
_ => {
10+
let mut left = 0;
11+
let mut right = nums.len() - 1;
12+
let mut pos = nums.len();
13+
14+
while left <= right && right != 0 {
15+
let mid = (left + right) / 2;
16+
if nums[mid] > target {
17+
right = if mid > 0 {mid - 1 } else { 0 }
18+
} else if nums[mid] < target {
19+
left = mid + 1
20+
} else {
21+
pos = mid;
22+
break
23+
}
24+
}
25+
26+
println!("{} {} {}", left, right, pos);
27+
if right == 0 && nums.last().unwrap() == &target {
28+
(nums.len() - 1) as i32
29+
} else if right ==0 && nums.first().unwrap() == &target {
30+
0
31+
} else {
32+
if pos < nums.len() && nums[pos] == target {
33+
return pos as i32
34+
} else {
35+
-1
36+
}
37+
}
38+
}
39+
}
40+
41+
42+
43+
44+
45+
}
46+
}
47+
48+
49+
50+
#[cfg(test)]
51+
mod tests {
52+
use super::*;
53+
54+
#[test] fn test_1 () {
55+
// assert_eq!(Solution::search(vec![-1,0,3,5,9,12], 9), 4);
56+
// assert_eq!(Solution::search(vec![-1,0,3,5,9,12], 2), -1);
57+
// assert_eq!(Solution::search(vec![2, 5], 0), -1);
58+
assert_eq!(Solution::search(vec![-1, 2, 5], -1), 0);
59+
}
60+
61+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /