Title Description:
For an unordered array A, design an algorithm to find the length of the shortest sub-array that needs to be sorted.
Given an integer array A and its size n, return the length of the shortest sub-array.
Test examples:
[1,5,3,4,2,6,7],7
Returns: 4
1 /*2 I'm feeling a little bit of a problem with this question on the Ox-guest web.3 because the default ascending sort! 4 the following implementation of the array [8,7,6,5,4,3] results will be 6,5 The result should actually be 0 at this point, because it's already orderly. 6 */7#include <iostream>8#include <vector>9 using namespacestd;Ten One intFindshortest (vector<int> A,intN) { A if(N <2) - return 0; - intmax = a[0]; the intR =-1; - for(inti =1; I < n; i++){ - if(Max >A[i]) -R =i; + Else -Max =A[i]; + } A if(r = =-1) at return 0; - intMin = a[n-1]; - intL =-1; - for(inti = n2; I >=0; i--){ - if(Min <A[i]) -L =i; in Else -Min =A[i]; to } + returnr-l+1; -}
1 //Test:2 intMain () {3vector<int>A;4 /*A.push_back (1);5 A.push_back (5);6 A.push_back (3);7 A.push_back (4);8 A.push_back (2);9 A.push_back (6);Ten A.push_back (7);*/ OneA.push_back (8); AA.push_back (7); -A.push_back (6); -A.push_back (5); theA.push_back (4); -A.push_back (3); -cout << Findshortest (A,6) <<Endl; - return 0; +}
2-1-Shortest sub-array length to be sorted