carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.
4 stars 1 forks source link

leetcode34:在排序数组中查找元素的第一个和最后一个位置(find_first_and_last_position_of_element_in_sorted_array_34) #136

Open carloscn opened 1 year ago

carloscn commented 1 year ago

问题描述

给你一个按照非递减顺序排列的整数数组 nums,和一个目标值 target。请你找出给定目标值在数组中的开始位置和结束位置。

如果数组中不存在目标值 target,返回 [-1, -1]。

你必须设计并实现时间复杂度为 O(log n) 的算法解决此问题。

示例 1:

输入:nums = [5,7,7,8,8,10], target = 8 输出:[3,4] 示例 2:

输入:nums = [5,7,7,8,8,10], target = 6 输出:[-1,-1] 示例 3:

输入:nums = [], target = 0 输出:[-1,-1]  

提示:

0 <= nums.length <= 105 -109 <= nums[i] <= 109 nums 是一个非递减数组 -109 <= target <= 109

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array

carloscn commented 1 year ago

问题分析

log(n)复杂度,强迫使用二分法。

fn find_first(array:&Vec<i32>, target:i32) -> Vec<i32>
{
    let mut ret_vec:Vec<i32> = vec![-1, -1];
    let mut left:usize = 0;
    let mut right:usize = array.len() - 1;
    let mut mid:usize = left + (right - left) / 2;

    while left <= right {
        if array[mid] < target {
            left = mid;
        } else if array[mid] > target {
            right = mid;
        } else {
            break;
        }
        mid = left + (right - left) / 2;
    }

    if (mid == 0) || (mid == array.len() - 1) {
        return ret_vec;
    }

    right = mid;
    left = mid;
    let mut is_left:bool = false;
    let mut is_right:bool = false;
    while (is_left == false) || (is_right == false) {
        if array[mid] == array[left] {
            left -= 1;
        } else {
            ret_vec[0] = (left + 1) as i32;
            is_left = true;
        }

        if array[mid] == array[right] {
            right += 1;
        }  else {
            ret_vec[1] = (right - 1) as i32;
            is_right = true;
        }
    }

    return ret_vec;
}
carloscn commented 1 year ago

code

https://review.gerrithub.io/c/carloscn/structstudy/+/550228 https://github.com/carloscn/structstudy/commit/3165bb7decdc4d57f4608f8ad0f12d79890b6827