解题报告:求数组的无序部分的长度

题目描述

对于一个无序数组A,请设计一个算法,求出需要排序的最短子数组的长度(假定排序后为升序)。
给定一个整数数组A及它的大小n,请返回最短需要排序的子数组的长度。

测试样例:
[1,5,3,4,2,6,7],7
返回:4

思路

可以从序列的单调性入手,对于任何一个有序单增序列,从右往左扫描得到的元素是单调不增的,从左往右扫描得到的元素是单调不减。
从右往左扫描,找到单调性反转的最左元素,就是无序序列的左端,从左往右扫描,找到单调性反转的最右元素,就是无序序列的右端。

代码

使用双指针

int findShortest(std::vector<int> A, int n)
{
    // the begin of the sub-array which is unsorted
    int begin = n-1;
    // the end of the sub-array which is unsorted
    int end = 0;

    int max = A[0], min = A[n-1];
    for(int i = 0; i < n; i++)
    {
        if(max <= A[i])
            max = A[i];
        else
            end = i;
    }
    for(int i = n-1;i >= 0;i--)
    {
        if(min >= A[i])
            min = A[i];
        else
            begin = i;
    }

    return begin < end ? end-begin+1 : 0;
}
posted @ 2020-03-17 15:51  joeyzzz  阅读(199)  评论(0编辑  收藏  举报