程式語言 - LeetCode - C++ - 581. Shortest Unsorted Continuous Subarray



題目:


解答:

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        vector<int> sorted(nums.begin(), nums.end());
        sort(sorted.begin(), sorted.end());

        int n = nums.size();
        int l = 0;
        int r = n - 1;

        while (l < n && nums[l] == sorted[l]) {
            l += 1;
        }

        if (l >= n) {
            return 0;
        }

        while (r >= 0 && nums[r] == sorted[r]) {
            r -= 1;
        }

        return r - l + 1;
    }
};