LeetCode 581 _ 最短无序连续子数组

1. 题目描述

2. 代码

 1 class Solution:
 2     def findUnsortedSubarray(self, nums: 'List[int]') -> int:
 3         n = len(nums)
 4         temp = sorted(nums)
 5         start,end = 0,n-1
 6         while start < n and temp[start] == nums[start]:
 7             start += 1
 8         while end > start and temp[end] == nums[end]:
 9             end -= 1
10         return end - start + 1

思路: 先利用sorted()排序获取一个新的列表temp, 然后对比temp和nums的元素.

         从左往右和从右往左, 分别找到第一个对应元素不同的2个索引, 然后索引相减+1即为所求无序数组的长度.

3. 整理

3.1sorted和sort

1 >>>sorted([5, 2, 3, 1, 4])
2 [1, 2, 3, 4, 5] 
1 >>>a=[5,2,3,1,4]
2 >>> a.sort()
3 >>> a
4 [1,2,3,4,5]

注:list 的 list.sort() 方法, 这个方法会修改原始的 list (返回值为None).

       list.sort() 方法只为 list 定义, 而 sorted() 函数可以接收任何的 iterable.

附b站一个讲解链接https://www.bilibili.com/video/BV1W4411V7W6?from=search&seid=8266600180645446873

原文地址:https://www.cnblogs.com/vvzhang/p/13830382.html