代码改变世界

[LeetCode] 581. Shortest Unsorted Continuous Subarray_Easy tag: Sort, Stack

2018-08-20 01:37  Johnson_强生仔仔  阅读(195)  评论(0编辑  收藏  举报

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:

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

 

这个题目用sort去跟之前的nums比较, 然后把第一个不相等和最后一个不相等的index找到, return r - l + 1如果>1的话, 否则为0.   

其次利用Stack, 把第一个不和谐的index找到, 再将nums reverse, 去找最后一个不和谐的index, return r - l + 1如果>1的话, 否则为0.   

 

Code

1) Sort     T: O(nlgn)    S: O(n)

class Solution:
    def findShortestSubarry(self, nums):
        nums_copy, l, r, lr = sorted(nums), len(nums)-1, 0, len(nums)
        for i in range(lr):
            if nums[i] != nums_copy[i]:
                l = min(l, i)
                r = max(r, i)
        ans = r-l + 1
        return ans if ans > 0 else 0

 

2. Stack   T: O(n)    S; O(n)

class Solution:
    def findShortestSubarry(self, nums):
        stack, l, r, lr = [], len(nums)-1, 0, len(nums)
        for i in range(lr):
            while stack and nums[stack[-1]] > nums[i]:
                l = min(l, stack.pop())
            stack.append(i)
        stack = []
        for i in range(lr)[::-1]:
            while stack and nums[stack[-1]] < nums[i]:
                r = max(r, stack.pop())
            stack.append(i)
        ans = r - l + 1
        return ans if ans > 0 else 0