[leetcode]581. Shortest Unsorted Continuous Subarray

[leetcode]581. Shortest Unsorted Continuous Subarray


Analysis

我爱西蓝花~—— [一辈子~]

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.
给定一个数组,给数组的一个子数组排序(升序),排序之后整个数组都是升序的,求这个子数组的长度。给原数组排序,然后比较排序后的数组和原数组就行了。

Implement

class Solution {
public:
    int findUnsortedSubarray(vector<int>& nums) {
        vector<int> nums_sort(nums.begin(), nums.end());
        sort(nums_sort.begin(), nums_sort.end());
        int len = nums.size();
        int t1=0, t2=0;
        for(int i=0; i<len; i++){
            if(nums[i] != nums_sort[i]){
                t1 = i;
                break;
            }
        }
        for(int i=len-1; i>t1; i--){
            if(nums[i] != nums_sort[i]){
                t2 = i;
                break;
            }
        }
        if(t1 == t2)
            return 0;
        return t2-t1+1;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_32135877/article/details/80972457