zoukankan      html  css  js  c++  java
  • 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.
    

    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 <=.

    Solution 1: 

    原数组为A, 排序后的数组记为B,比较A[i]与B[i],找到第一个和最后一个不一致的位置i与j,返回j-i+1. 这种解法比较直观,O(nlogn)的时间复杂度,空间复杂度为O(n). 比较直观,不提供代码。

    Solution 2:

    从左向右扫描数组,一直更新max,找到最后(数组右侧)一个小于max的数,其下标记为end;

    从右向左扫描数组,一直更新min,找到最后(数组左侧)一个大于min的数,其下标记为start;

    返回end-start+1.

    如果数组已是ascending状态,需返回0. 为了重用 return end-start+1,在设置end和start的初始值时应注意相对大小。

     1 public class Solution {
     2     public int findUnsortedSubarray(int[] nums) {
     3         int n = nums.length;
     4         int maxNum = nums[0], minNum = nums[n - 1];
     5         int end = -2, start = -1; // in case the array is already sorted
     6         
     7         for (int i = 1; i < n; i++) {
     8             maxNum = Math.max(maxNum, nums[i]);
     9             if (maxNum > nums[i]) end = i;
    10             
    11             minNum = Math.min(minNum, nums[n - 1 - i]);
    12             if (minNum < nums[n - 1 - i]) start = n - 1 - i;
    13         }
    14         return end - start + 1;
    15     }
    16 }
     
  • 相关阅读:
    butterknife异常提示:attribute value must be constant
    SharedPreferences第一次使用后HashMap将常驻内存
    js获取元素的innerText属性为什么为空
    针对focus和blur的Dom事件触发顺序
    android中View的GONE和INVISIBLE的原理
    HTML中div以及span等元素获取焦点
    android MotionEvent获得当前位置
    IE10 透明背景的div无法遮罩
    jquery中.attr('value')和.val()的区别
    __proto__和protaotype的区分
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6919450.html
Copyright © 2011-2022 走看看