581. Shortest Unsorted Continuous Subarray

Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.

Return the shortest such subarray and output its length.

 

Example 1:

Input: nums = [2,6,4,8,10,9,15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.

Example 2:

Input: nums = [1,2,3,4]
Output: 0

Example 3:

Input: nums = [1]
Output: 0

 

Constraints:

  • 1 <= nums.length <= 104
  • -105 <= nums[i] <= 105

 

Follow up: Can you solve it in O(n) time complexity?

Rust Solution

struct Solution;

use std::i32;

impl Solution {
    fn find_unsorted_subarray(nums: Vec<i32>) -> i32 {
        let n = nums.len();
        let mut min = i32::MAX;
        let mut max = i32::MIN;
        let mut l = n - 1;
        let mut r = 0;

        for i in 0..n {
            max = i32::max(max, nums[i]);
            if max != nums[i] {
                r = i;
            }
        }

        for i in (0..n).rev() {
            min = i32::min(min, nums[i]);
            if min != nums[i] {
                l = i;
            }
        }
        if r <= l {
            0
        } else {
            (r - l + 1) as i32
        }
    }
}

#[test]
fn test() {
    let nums = vec![2, 6, 4, 8, 10, 9, 15];
    assert_eq!(Solution::find_unsorted_subarray(nums), 5);
    let nums = vec![1, 2, 3, 4, 5];
    assert_eq!(Solution::find_unsorted_subarray(nums), 0);
}

Having problems with this solution? Click here to submit an issue on github.