题目:
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too.
You need to find the shortest such subarray and output its length.
分析:
- 要寻找未排序好的子串,首先要有排序好的递增子串,python自带排序算法时间复杂度O(nlgn),在所有排序算法中平均时间复杂度最优;
- 分别从前、后遍历列表,通过寻找第一个不在自己应该在的位置的元素,他们的对应索引依次为要寻找子串的开始与结尾索引
- 计算子串长度
代码:
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sortNums = sorted(nums)
if nums == sortNums:
return 0
#print sortNums
beginIdx = 0
endIdx = 0
for i,x in enumerate(nums):
if x != sortNums[i]:
beginIdx = i
break
for j in range(len(nums))[::-1]:
if nums[j] != sortNums[j]:
endIdx = j + 1
break
return endIdx - beginIdx
思考:
- 通过前向遍历寻找结束索引或从后向遍历寻找开始索引通常不可取
- 要寻找的子串越长,此算法耗时越短
- 讨论区有很多简短的代码,具有固定的时间复杂度,为了代码的简洁,牺牲了运行效率,本代码提交时由于91%