carloscn / structstudy

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

leetcode1909: Remove One Element to Make the Array Strictly Increasing #305

Open carloscn opened 1 year ago

carloscn commented 1 year ago

Description

Given a 0-indexed integer array nums, return true if it can be made strictly increasing after removing exactly one element, or false otherwise. If the array is already strictly increasing, return true.

The array nums is strictly increasing if nums[i - 1] < nums[i] for each index (1 <= i < nums.length).

Example 1:

Input: nums = [1,2,10,5,7] Output: true Explanation: By removing 10 at index 2 from nums, it becomes [1,2,5,7]. [1,2,5,7] is strictly increasing, so return true.

Example 2:

Input: nums = [2,3,1,2] Output: false Explanation: [3,1,2] is the result of removing the element at index 0. [2,1,2] is the result of removing the element at index 1. [2,3,2] is the result of removing the element at index 2. [2,3,1] is the result of removing the element at index 3. No resulting array is strictly increasing, so return false.

Example 3:

Input: nums = [1,1,1] Output: false Explanation: The result of removing any element is [1,1]. [1,1] is not strictly increasing, so return false.

Constraints:

2 <= nums.length <= 1000 1 <= nums[i] <= 1000

carloscn commented 1 year ago

Analysis

pub fn can_be_increasing(nums: Vec<i32>) -> bool
{
    if nums.len() < 1 {
        return false;
    }
    let mut ret:bool = false;
    let mut i:usize = 0;

    while i < nums.len() - 1 {
        if nums[i + 1] - nums[i] <= 0 {
            if ret == false &&
               i >= 1 &&
               nums[i + 1] - nums[i - 1] >= 0 {
                ret = true;
            } else {
                return false;
            }
        }
        i += 1;
    }

    return true;
}
carloscn commented 1 year ago

Code

https://review.gerrithub.io/c/carloscn/structstudy/+/1167444 https://github.com/carloscn/structstudy/commit/f34491e92d9dc5af25774e8020817d3f6318091a