leetcode 581

Posted thunderdog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 581相关的知识,希望对你有一定的参考价值。

https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/

solution 1

 

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        vector<int> t = nums;
        sort(t.begin(), t.end());
        int start = 0, end = nums.size() -1;
        while (start < nums.size() && t[start] == nums[start]) ++start;
        // cout << start << endl;
        while (end > start &&t[end] == nums[end]) --end;
        // cout << end << endl;
        return end - start + 1;
    }
};

solution 2

class Solution {
public:
    // max递增序列最大值,从头开始
    // min递减序列最小值,从尾开始
    // end 从前向后扩展,start从后向前扩展
    // 理解为寻找逆序对的end和start位置
    // 当前数若是小于递增序列的最大值,则存在逆序对
    int findUnsortedSubarray(vector<int>& nums) {
        int n = nums.size();
        int start = 0, end = -1;
        int max = nums[0], min = nums[n - 1];
        for (int i = 0; i < n; ++i) {
            if (max > nums[i]) {
                end = i;
            } else {
                max = nums[i];
            }
            if (min < nums[n - i - 1]) {
                start = n - i - 1;
            } else {
                min = nums[n - i -1];
            }
            // cout << i <<" : " << end <<" " << start << endl;
        }
        // cout << end << " " << start << endl;
        return end - start + 1;
    }
};

 

以上是关于leetcode 581的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 581

LeetCode 581. 最短无序连续子数组(Shortest Unsorted Continuous Subarray)

581. Shortest Unsorted Continuous Subarray (LeetCode)

LeetCode - 581. Shortest Unsorted Continuous Subarray

leetcode581 最短无序连续子数组(Easy不简单)

Leetcode 581.最短无序连续子数组