581. Shortest Unsorted Continuous Subarray

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

题目:

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:

  1. Then length of the input array is in range [1, 10,000].
  2. The input array may contain duplicates, so ascending order here means <=.
思路:

本题主要利用如下思路(简单直接):

step1:先利用C++ sort函数进行升序排序,维护两个变量first及end,并赋予初始值0,-1(防止数组本来就是升序有序的情况)

step2:从数组尾部遍历数组,利用end记录升序后数组与原先数组第一个不相同的值的下标

step3:从数组头部遍历数组,利用first记录升序后数组与原先数组第一个不相同的值的下标

step4:返回end-first+1

代码:

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


阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6