zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    洛谷 1842 [USACO05NOV]奶牛玩杂技【贪心】
    洛谷 1757 通天之分组背包【分组背包】
    洛谷 1330 封锁阳光大学
    洛谷 1019 单词接龙
    【模板】CDQ分治
    BZOJ 2734 洛谷 3226 [HNOI2012]集合选数【状压DP】【思维题】
    BZOJ 2457 [BeiJing2011]双端队列
    洛谷 2015 二叉苹果树
    牛客网 牛可乐发红包脱单ACM赛 C题 区区区间间间
    牛客网 牛可乐发红包脱单ACM赛 B题 小a的旅行计划
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8905772.html
Copyright © 2011-2022 走看看