[LeetCode] 581. Shortest Unsorted Continuous Subarray

来源:互联网 发布:python strip 多个 编辑:程序博客网 时间:2024/05/16 10:53

Given an integer array, 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, too.

You need to find the shortest such subarray and output its length.

Example 1:
Input: [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.
Note:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.

// base versionclass Solution {public:    int findUnsortedSubarray(vector<int>& nums) {        int n = nums.size();        vector<int> sorted(nums.begin(), nums.end());        int i = 0, j = n - 1;        while (i < n && nums[i] == sorted[i]) i++;        while (j > i && nums[j] == sorted[j]) j--;        return j - i + 1;    }};
/* * 在上述代码的基础之上,进行了优化。 * 对于左侧的nums[i],我们只需要保证nums[i]为[i, n)这个范围内的最小值即可。 * 对于右侧的nums[j],我们只需要保证nums[j]为[0, j]为这个范围内的最大值即可。 * 为此,构建以下两个数组. * Mini2n[i]: 表示在[i, n)这个范围内的最小元素值 * Max02j[j]: 表示在[0, j)这个范围内的最大元素值 */class Solution {public:    int findUnsortedSubarray(vector<int>& nums) {        const int n = nums.size();        vector<int> Mini2n(n), Max02j(n);        for (int i = n - 1, MinVal = INT_MAX; i >= 0; i--)            Mini2n[i] = MinVal = min(nums[i], MinVal);        for (int j = 0, MaxVal = INT_MIN; j < n; j++)            Max02j[j] = MaxVal = max(nums[j], MaxVal);        int i = 0, j = n - 1;        while (i < n && nums[i] <= Mini2n[i])            i++;        while (j > i && nums[j] >= Max02j[j])            j--;        return j - i + 1;    }};

这里写图片描述这里写图片描述

阅读全文
0 0
原创粉丝点击