581. Shortest Unsorted Continuous Subarray

来源:互联网 发布:手机淘宝店铺怎么激活 编辑:程序博客网 时间:2024/05/22 03:02

题目来源【Leetcode】

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 <=.
直接放代码:

class Solution {public:    int findUnsortedSubarray(vector<int>& nums) {        vector<int>temp(nums);        sort(nums.begin(), nums.end());        int judge = 0;        int count1  = 0;        int count2 = 0;        for(int i = 0; i < nums.size(); i++){            if(temp[i] != nums[i]){                count1 = i;                break;            }             else judge++;        }        for(int i = nums.size()-1 ; i >= 0; i -- ){           if(temp[i] != nums[i]){                count2 = nums.size()-i-1;                break;            }         }        if(count1 == 0 && count2 == 0 && judge == nums.size()) return 0;        else        return nums.size()-count1-count2;    }};