zoukankan      html  css  js  c++  java
  • 2-1-需排序的最短子数组长度

    题目描述:
      对于一个无序数组A,请设计一个算法,求出需要排序的最短子数组的长度。
      给定一个整数数组A及它的大小n,请返回最短子数组的长度。
    测试样例:
      [1,5,3,4,2,6,7],7
      返回:4

     1 /*
     2     这个题在牛客网上的讲解我感觉是有点问题的,
     3     因为默认了升序排序!
     4     如下实现对数组[8,7,6,5,4,3]的结果将会是6,
     5     实际上此时的结果应该为0,因为现在已经是有序的了。
     6 */
     7 #include <iostream>
     8 #include <vector>
     9 using namespace std;
    10 
    11 int findShortest(vector<int> A, int n) {
    12     if (n < 2)
    13         return 0;
    14     int max = A[0];
    15     int r = -1;
    16     for (int i = 1; i < n; i++){
    17         if (max > A[i])
    18             r = i;
    19         else
    20             max = A[i];
    21     }
    22     if (r == -1)
    23         return 0;
    24     int min = A[n-1];
    25     int l = -1;
    26     for (int i = n-2; i >= 0; i--){
    27         if (min < A[i])
    28             l = i;
    29         else
    30             min = A[i];
    31     }
    32     return r-l+1;
    33 }
     1 // test:
     2 int main(){
     3     vector<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);
    10     a.push_back(7);*/
    11     a.push_back(8);
    12     a.push_back(7);
    13     a.push_back(6);
    14     a.push_back(5);
    15     a.push_back(4);
    16     a.push_back(3);
    17     cout << findShortest(a, 6) << endl;
    18     return 0;
    19 }
  • 相关阅读:
    判断奇偶
    数据库中去重时:建议使用group by
    将博客搬至CSDN
    FileZilla
    Windows通过VNC连接并显示Linux桌面(Ubuntu16.04)
    springMVC 中参数绑定
    get和post的区别主要有以下几方面
    Get、Post、Put与Delete的区别
    HTTP请求地址映射
    Spring MVC 框架
  • 原文地址:https://www.cnblogs.com/qianmacao/p/4884749.html
Copyright © 2011-2022 走看看