581. Shortest Unsorted Continuous Subarray连续数组中的递增异常情况

[抄题]:

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.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

题目有歧义:其实没有“最短”的概念,找到一个范围就行了

[奇葩corner case]:

1234,输出0。因此i小j大的初始值是-1,0。别的地方不知道能否试试?

[思维问题]:

指针对撞一直走,但是没想到最后会ij颠倒大小。

[一句话思路]:

i小j大变成了i大j小,所以结果是i - j + 1

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 不可能i j,l r两对指针同时走的,一对就

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

指针对撞一直走,但是没想到最后会ij颠倒大小。i - j + 1

[复杂度]:Time complexity: O(n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[关键模板化代码]:

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

class Solution {
    public int findUnsortedSubarray(int[] nums) {
        //cc
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        //ini: l r
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE, i = -1, j = 0;
        
        //for loop
        for (int l = 0, r = nums.length - 1; r >= 0; l++, r--) {
            max = Math.max(nums[l], max);
            if (nums[l] != max) {
                i = l;
            }
            
            min = Math.min(nums[r], min);
            if (nums[r] != min) {
                j = r;
            }
        }
        
        return i - j + 1;
    }
}
View Code

 

posted @ 2018-04-22 09:22  苗妙苗  阅读(99)  评论(0编辑  收藏  举报