Bootstrap

LeetCode系列581—最短无序连续子数组

题意

581. 最短无序连续子数组

题解

方法一:辅助数组

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        vector<int> nums_min(nums.size());
        vector<int> nums_max(nums.size());
        int min = 100001, max = -100001;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] > max) max = nums[i];
            nums_max[i] = max;
        }
        for (int i = nums.size() - 1; i >= 0; i--) {
            if (nums[i] < min) min = nums[i];
            nums_min[i] = min;
        }
        int left = 0, right = nums.size() - 1;
        while(left <= right) {
            int flag =.0;
            if (nums[left] == nums_min[left]) {
                flag = 1;
                left++;
            }
            if (nums[right] == nums_max[right]) {
                flag = 1;
                right--;
            }
            if (flag == 0) break;
        }
        return right - left + 1 < 0 ? 0 : right - left + 1;
    }
};

时间复杂度:O(n)
空间复杂度:O(n)

方法二:排序

排序后找相同的前缀和后缀

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        if (is_sorted(nums.begin(), nums.end())) {
            return 0;
        }
        vector<int> numsSorted(nums);
        sort(numsSorted.begin(), numsSorted.end());
        int left = 0;
        while (nums[left] == numsSorted[left]) {
            left++;
        }
        int right = nums.size() - 1;
        while (nums[right] == numsSorted[right]) {
            right--;
        }
        return right - left + 1;
    }
};

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/solution/zui-duan-wu-xu-lian-xu-zi-shu-zu-by-leet-yhlf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

方法三:一次遍历

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        int n = nums.size();
        int maxn = INT_MIN, right = -1;
        int minn = INT_MAX, left = -1;
        for (int i = 0; i < n; i++) {
            if (maxn > nums[i]) {
                right = i;
            } else {
                maxn = nums[i];
            }
            if (minn < nums[n - i - 1]) {
                left = n - i - 1;
            } else {
                minn = nums[n - i - 1];
            }
        }
        return right == -1 ? 0 : right - left + 1;
    }
};

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/shortest-unsorted-continuous-subarray/solution/zui-duan-wu-xu-lian-xu-zi-shu-zu-by-leet-yhlf/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
;