题目:581. 最短无序连续子数组
给你一个整数数组 nums ,你需要找出一个 连续子数组 ,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
请你找出符合题意的 最短 子数组,并输出它的长度。
解答:
int findUnsortedSubarray(int* nums, int numsSize)
{
int i,j,min,max;//游标和定位
int posi=0;
int posj=numsSize-1;
// 找到连续子数组的起始位置
while(posj>posi && nums[posi]<=nums[posi+1])
posi++;
// 找到连续子数组的末尾位置
while(posj>posi && nums[posj]>=nums[posj-1])
posj--;
// 此时数组已经有序
if(posi==posj)
return 0;
// 找到连续子数组中最大最小值
// 接下来的程序是为了防止数据相同的情况
// 如:[1,3,2,2,2]
// 直接终止程序,posi=1,posj=2,程序返回2
// 但是应该输出4
min=nums[posi];
max=nums[posj];
for(i=posi;i<=posj;i++)
{
if(nums[i]<min)
min=nums[i];
if(nums[i]>max)
max=nums[i];
}
posi=0;
posj=numsSize-1;
// 找到连续子数组的边界值
// 连续子数组的起始位置
while(nums[posi]<=min)
posi++;
// 连续子数组的末尾位置
while(nums[posj]>=max)
posj--;
return posj-posi+1;
}