rustgym/leetcode/
_34_find_first_and_last_position_of_elements_in_sorted_array.rs1struct Solution;
2
3impl Solution {
4 fn search_range(nums: Vec<i32>, target: i32) -> Vec<i32> {
5 let n = nums.len();
6 match nums.binary_search(&target) {
7 Ok(i) => {
8 let mut l = i;
9 let mut r = i;
10 while l > 0 && nums[l - 1] == target {
11 l -= 1;
12 }
13 while r + 1 < n && nums[r + 1] == target {
14 r += 1;
15 }
16 vec![l as i32, r as i32]
17 }
18 Err(_) => vec![-1, -1],
19 }
20 }
21}
22
23#[test]
24fn test() {
25 let nums = vec![5, 7, 7, 8, 8, 10];
26 let target = 8;
27 let res = vec![3, 4];
28 assert_eq!(Solution::search_range(nums, target), res);
29}