Find Length of Shortest Sequence

Description You are given an array of integers, find the length of the shortest sequence you need to sort to make all the elements of the array in order. A shortest sequence is a minimum unsorted sub-array indices M and N so that the entire array would be sorted if you sort elements M through N.

Input The input should be N non-negative integers, where N should be less than 100,000. Each integer should be less than or equal to 2,147,483,647.

Output The output should be the length of the shortest sequence.

Sample Input 1 2 5 4 6

Sample Output 2

想到做起来真的太简单了!!

class Solution {
public:
    int getShortestSequenceLength(const vector<int> &a) {
        int maxIdx=-1,maxVal=a[0];

        for(int i=0;i<a.size();i++)
        {
            maxVal=max(maxVal,a[i]);
            if(maxVal!=a[i])maxIdx=i;
        }

        int minIdx=-1,minVal=a.back();
        for(int i=a.size()-1;i>=0;i--)
        {
            minVal=min(minVal,a[i]);
            if(minVal!=a[i])minIdx=i;
        }

        if(maxIdx==-1)return 0;
        else return maxIdx-minIdx+1;
    }
};

results matching ""

    No results matching ""