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

 

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

 


 

题目标签:Array

  题目给了我们一个nums array, 让我们找出一个最短的无序连续子数组,当我们把这个子数组排序之后,整个array就已经是排序的了。

  要找到这个子数组的范围,先要了解这个范围的beg 和 end 是如何定义的。

  来看这个例子:1 3 5 7 2 4 5 6

  a. 当我们找到第一个违反ascending 排序的数字 2的时候,我们不能是仅仅把beg 标记为2的前面一个数字7,而是要一直往前,找到一个合适的位置,找到在最前面位置的比2大的数字,这里是3。

  b. 同样的,为了找end, 那么我们要从7的后面开始找,一直找到一个最后面位置的比7小的数字,这里是6。

  这样的话,范围就是3到6 是我们要找的子数组。把3到6排序完了之后,整个array 就已经是排序的了。

 

  这里我们可以发现,2是min, 7是max,所以我们可以分两个方向来分别寻找beg 和end。

  从右到左(绿色),维护更新min 和 beg;

  从左到右(红色),维护更新max 和 end。

 

 

Java Solution:

Runtime beats 89.16% 

完成日期:10/15/2017

关键词:Array

关键点:分别以两个方向来找到beg 和 end

 1 class Solution 
 2 {
 3     public int findUnsortedSubarray(int[] nums) 
 4     {
 5         int n = nums.length;
 6         int beg = -1;
 7         int end = -2; // end is -2 is because it works if the array is already in ascending order
 8         int min = nums[n-1]; // from right to left
 9         int max = nums[0];      // from left to right
10         
11         for(int i=0; i<n; i++)
12         {
13             max = Math.max(max, nums[i]);
14             min = Math.min(min, nums[n-1-i]);
15             
16             if(nums[i] < max)
17                 end = i;
18             if(nums[n-1-i] > min)
19                 beg = n-1-i;
20         }
21         
22         return end - beg + 1; // if array is already in ascending order, -2 - (-1) + 1 = 0
23     }
24 }

参考资料:

https://discuss.leetcode.com/topic/89282/java-o-n-time-o-1-space

 

LeetCode 题目列表 - LeetCode Questions List

 

转载于:https://www.cnblogs.com/jimmycheng/p/7673733.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值