Find First and Last Position of Element in Sorted Array in Rust

impl Solution {
    pub fn search_range(nums: Vec<i32>, target: i32) -> Vec<i32> {
        // Function to find the first occurrence of the target
        fn find_first(nums: &[i32], target: i32) -> i32 {
            let (mut left, mut right) = (0, nums.len() as i32 - 1);
            let mut first_occurrence = -1;
            while left <= right {
                let mid = left + (right - left) / 2;
                if nums[mid as usize] == target {
                    first_occurrence = mid;
                    right = mid - 1; // Continue searching to the left
                } else if nums[mid as usize] < target {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
            first_occurrence
        }

        // Function to find the last occurrence of the target
        fn find_last(nums: &[i32], target: i32) -> i32 {
            let (mut left, mut right) = (0, nums.len() as i32 - 1);
            let mut last_occurrence = -1;
            while left <= right {
                let mid = left + (right - left) / 2;
                if nums[mid as usize] == target {
                    last_occurrence = mid;
                    left = mid + 1; // Continue searching to the right
                } else if nums[mid as usize] < target {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
            last_occurrence
        }

        // Handle the edge case of an empty array
        if nums.is_empty() {
            return [-1, -1].to_vec();
        }

        [find_first(&nums, target), find_last(&nums, target)].to_vec()
    }
}

PrevNext