Skip to content

Files

Latest commit

 

History

History
65 lines (48 loc) · 1.89 KB

581-shortest-unsorted-continuous-subarray.md

File metadata and controls

65 lines (48 loc) · 1.89 KB

581. Shortest Unsorted Continuous Subarray - 最短无序连续子数组

给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。

你找到的子数组应是最短的,请输出它的长度。

示例 1:

输入: [2, 6, 4, 8, 10, 9, 15]
输出: 5
解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序。

说明 :

  1. 输入的数组长度范围在 [1, 10,000]。
  2. 输入的数组可能包含重复元素 ,所以升序的意思是<=。

题目标签:Array

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
python3 124 ms N/A
class Solution:
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        '''
        排序前:[2, 6, 4, 8, 10,  9, 15]
        排序后:[2, 4, 6, 8,  9, 10, 15]
        思路:排序前后首尾比对
        '''
        snums = sorted(nums)
        cnt = 0
        for i in range(len(nums)):
            if nums[i] == snums[i]:
                cnt += 1
            else:
                break
        for j in range(len(nums)-1, i, -1):
            if nums[j] == snums[j]:
                cnt += 1
            else:
                break
        return len(nums) - cnt