[LeetCode] 581. Shortest Unsorted Continuous Subarray
程序员文章站
2024-02-24 15:09:54
...
题目内容
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.
Example 1:
Input: [2, 6, 4, 8, 10, 9, 15]
Output: 5
Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
题目思路
这道题目可以先获得一个正确的进行比较。需要确定两个变量,第一个是左侧变量,第二个是持续到最右侧的位置的变量,取最大值。也就是当遇到第一个的时候,同时改变两个变量。然后依次向后遍历,知道末尾为止,如果遇到不等就改变第二变量的数值
程序代码
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
tnums=sorted(nums)
left,right=-1,-1
for i in range(len(nums)):
if nums[i]!=tnums[i]:
if left==-1:
left=i
right=i
return right-left+1 if right!=left else 0
推荐阅读
-
[easy][Array]581. Shortest Unsorted Continuous Subarray
-
581. Shortest Unsorted Continuous Subarray
-
581. Shortest Unsorted Continuous Subarray
-
581. Shortest Unsorted Continuous Subarray
-
[LeetCode] 581. Shortest Unsorted Continuous Subarray
-
581. Shortest Unsorted Continuous Subarray
-
581. Shortest Unsorted Continuous Subarray
-
Leetcode0523--Continuous Subarray Sum 连续和倍数
-
LeetCode题解——862.Shortest Subarray with Sum at Least K
-
leetcode 523. Continuous Subarray Sum