​welcome to my blog​

LeetCode Top 100 Liked Questions 581. Shortest Unsorted Continuous Subarray (Java版; Easy)

题目描述

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:
Then length of the input array is in range [1, 10,000].
The input array may contain duplicates, so ascending order here means <=.
class Solution {
public int findUnsortedSubarray(int[] nums) {
int n = nums.length;
int R=0, L=n-1;
int max = nums[0];
for(int i=0; i<n; i++){
if(nums[i] >= max){
max = nums[i];
}else{
R = i;
}
}
int min = nums[n-1];
for(int i=n-1; i>=0; i--){
if(nums[i]<=min){
min = nums[i];
}else{
L = i;
}
}

return R>L? R-L+1 : 0;
}
}

第一次做

/*
从左往右遍历数组, 记录arr[i]左侧的最大值, 如果arr[i]>=max, 就更新max,
如果arr[i]<max, 则使用变量rightBorder记录索引i; 遍历结束后,rightBorder右侧的部分不需要排序.
(rightBorder左侧的部分可能需要全部排序或者部分排序,需要根据从右往左遍历的结果决定)

从右往左遍历数组, 记录arr[i]右侧的最小值, 如果arr[i]<=min, 就更新min,
如果arr[i]>min, 则使用变量leftBorder记录索引i; 遍历结束后, leftBorder左侧的部分不需要排序

这两遍遍历做的事情: 找到递增的部分
*/
class Solution {
public int findUnsortedSubarray(int[] nums) {
//input check
if(nums==null || nums.length==0)
return 0;
//
int max=Integer.MIN_VALUE, min=Integer.MAX_VALUE;
int rightBorder=-1, leftBorder=nums.length;
//从左往右遍历
for(int i=0; i<nums.length; i++){
if(nums[i]>=max)
max = nums[i];
else
rightBorder = i;
}
//从右往左遍历
for(int i=nums.length-1; i>=0; i--){
if(nums[i]<=min)
min = nums[i];
else
leftBorder = i;
}
return rightBorder > leftBorder ? rightBorder-leftBorder+1 : 0;
}
}