[GeeksForGeeks] Minimum length unsorted subarray, sorting which makes the array sorted

Given an array, find the minimum length unsorted subarray. After soring this unsorted subarray,

the whole array is sorted.

 

Example, if the input array is [10, 12, 20, 30, 25, 40, 32, 31, 45, 50, 60], your program should be 

able to find that the minimum length unsorted subarray lies between the indices 3 and 7.

 

Solution 1. O(n * logn) runtime, O(n) space

1. make a copy of the given array.

2. sort the copy.

3. find the first and last indices where the given array and its sorted copy don't match .

 

Solution 2. O(n) runtime, O(1) space

The core idea of this solution is to first find the start index i of the unsorted subarray where arr[i] < arr[i- 1], 

and use arr[i - 1] as the current max value. 

Then keep scaning the rest of the array, as long as arr[i] < arr[i - 1] or arr[i] is smaller than the max value, 

we know that arr[i] is not in its sorted place. Update end index to i.

If arr[i] is bigger than max, update the current max to arr[i].

 

 1 public int[] getMinLenUnsortedSubarray(int[] arr) {
 2     int[] r = {-1, -1};
 3     if(arr == null || arr.length <= 1) {
 4         return r;
 5     }
 6     int i = 1;
 7     for(; i < arr.length; i++){
 8         if(arr[i] < arr[i - 1]) {
 9             break;
10         }
11     }
12     if(i == arr.length - 1){
13         return r;            
14     }
15     r[0] = i - 1;
16     r[1] = i;
17     int max = arr[i - 1];
18     for(i++; i < arr.length; i++){
19         if(arr[i] < arr[i - 1] || arr[i] < max){
20             r[1] = i;
21         }
22         else if(arr[i] >= max){
23             max = arr[i];
24         }
25     }
26     return r;
27 }

 

转载于:https://www.cnblogs.com/lz87/p/7337204.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值