题目描述
https://leetcode-cn.com/problems/sub-sort-lcci/
思路题解
设置一个low,一个high代表最后返回的数组切片的索引。该切片满足如下条件:
1.[low,high]内最小值>=array[low-1],且array[0,low-1]有序
2.[low,high]内最大值>=array[high+1],且array[high+1,len(array)-0]有序
于是先定位切片长度最小的[low,high],再求出切片内部的最大最小值:max_num、min_num。此时剪枝剪掉空数组、本来就是有序的情况和完全无序的情况。
再剪枝剪掉low和high其中有一方为边界的情况。
最后一个while循环,假设原来的切片长度为s,那么
s+1有2种情况:
[low-1,high]、[low,high+1]
s+2有3种情况:
[low-2,high]、[low,high+2]、[low-1,high+1]
对这五种情况按顺序判断,若符合条件则return当前的[low,high]。
代码如下:
class Solution:
def subSort(self, array: List[int]) -> List[int]:
#空数组
if not array:return[-1,-1]
low,high=0,len(array)-1
while(low<high and array[low]<=array[low+1]):
low+=1
#本来就有序
if low==high:
return [-1,-1]
while(array[high]>=array[high-1]):
high-=1
#完全无序
if low==0 and high==len(array)-1:
return [low,high]
min_num=min(array[low:high+1])
max_num=max(array[low:high+1])
#low、high其中之一为边界的情况
if low==0:
while high<=len(array)-2:
if max_num<=array[high+1]:
return [low,high]
high+=1
return [low,high]
if high==len(array)-1:
while low>=1:
if min_num>=array[low-1]:
return [low,high]
low-=1
return [low,high]
while low>=1 and high<=len(array)-2:
if array[low-1]<=min_num and array[high+1]>=max_num:
return [low,high]
#左边拓展一位
if low-2>=0 and array[low-2]<=min(min_num,array[low-1]) and array[high+1]>=max_num:
return [low-1,high]
#右边拓展一位
if high+2<=len(array)-1 and array[low-1]<=min_num and array[high+2]>=max(max_num,array[high+1]):
return [low,high+1]
#左边拓展2位
if low-3>=0 and array[low-3]<=min(min_num,array[low-2]) and array[high+1]>=max_num:
return [low-2,high]
#右边拓展2位
if high+3<=len(array)-1 and array[low-1]<=min_num and array[high+3]>=max(max_num,array[high+1]):
return [low,high+2]
#都不满足,左右各拓展一位
min_num=min(min_num,array[low-1])
max_num=max(max_num,array[high+1])
low-=1
high+=1
return [-1,-1]