[LeetCode] 538. Convert BST to Greater Tree

题:https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/

题目

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.

Note:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.

思路

题目大意

对于原 array ,从中找一个 子array,对该子array进行升序排序后,原array也为升序。

解题思路

对原array进行升序排序生成 tarray,分别从头,从尾部,将tarray与原array对比,设 得到 原array与 tarray 不同的 元素位置分别为 istart 、iend。

若 istart > iend 则原 array已经升序,return 0;否则,return iend - istart + 1

code

class Solution:
    def findUnsortedSubarray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """

        sortedarray = sorted(nums)
        nlen = len(nums)

        istart = 0 
        iend = len(nums)-1

        while istart < nlen and nums[istart] == sortedarray[istart]:
            istart += 1
        while iend >=0 and nums[iend] == sortedarray[iend]:
            iend -= 1
        if iend < istart:
            return 0
        return iend - istart + 1

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/82344371