• 第二章 排序 || 第19节 最短子数组练习题


    题目

    
    对于一个数组,请设计一个高效算法计算需要排序的最短子数组的长度。
    
    给定一个int数组A和数组的大小n,请返回一个二元组,代表所求序列的长度。(原序列位置从0开始标号,若原序列有序,返回0)。保证A中元素均为正整数。
    测试样例:
    
    [1,4,6,5,9,10],6
    
    返回:2
    
    

    解析

    • C++版
    class Subsequence {
    public:
        int shortestSubsequence(vector<int> A, int n) {
            // write code here
            int start=0;
            int end=n-1;
            //最右边比max值小的数的下标
            //最左边比min大的数的下标 
            //测试用例:[1,2,10,1,8,9],6
            int max=A[0],min=A[n-1];//记录两边已经遍历过的极值
            for(int i=0;i<n;i++)
                if(A[i]<max)
                    start=i;
                else
                    max=(max>A[i])?max:A[i];
            for(int j=n-1;j>=0;j--)
                if(A[j]>min)
                    end=j;
                else
                    min=(min<A[j])?min:A[j];
            if(start<=end)
                return 0;
            else
                return start-end+1;
        }
    };
    
    • 错误的思想:直接从左右两边逆序记录位置不对,需要找到全局极值
    class Subsequence {
    public:
        int shortestSubsequence(vector<int> A, int n) {
            // write code here
            int start=0;
            int end=n-1;
            for(int i=0;i<n-1;i++)
                if(A[i]>A[i+1])
                {
                    start=i;
                    break;
                }
            if(start==0&&A[n-2]<=A[n-1])
                return 0;
            for(int j=n-1;j>=start;j--)
            {
                if(A[j]<A[j-1])
                {
                    end=j;
                    break;
                }
            }
            int res=end-start+1;
            return res;
        }
    };
    
    测试用例:
    [1,2,10,1,8,9],6
    
    对应输出应该为:
    
    5
    
    你的输出为:
    
    2
    
  • 相关阅读:
    PostgreSQL14 规格严格
    yum方式安装nginx 规格严格
    PostgreSQL14 安装配置 规格严格
    PostgreSQL14 安装配置
    [RxJS] merge build count down example
    [Typescript] Declare Module
    [Typescript] export = and import = require()
    [HTML 5] HTML List
    [Typescript] 67. Medium Chunk
    [Typescript] TypeScript module Augmentation
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/9281884.html
Copyright © 2020-2023  润新知