2-1-Shortest sub-array length to be sorted

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.