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 }
     
  • 相关阅读:
    Java-io流入门到精通详细总结
    Java网络编程总结
    递归--逆波兰表达式
    递归--N皇后问题
    递归--汉诺塔问题 (Hanoi)
    递归--求n!的阶乘结果
    枚举--熄灯问题
    枚举--假币问题
    枚举--生理周期
    枚举--完美立方Python算法实现
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/6919450.html
Copyright © 2011-2022 走看看