- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathShortestUnsortedContiguousSubarray.java
More file actions
Latest commit
84 lines (71 loc) · 2.22 KB
/
Copy pathShortestUnsortedContiguousSubarray.java
File metadata and controls
84 lines (71 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
packageLeetcode;
/**
*
* @author kalpak
* Given an integer array nums, 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.
*
* Return the shortest such subarray and output its length.
*
*
*
* Example 1:
*
* Input: nums = [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.
* Example 2:
*
* Input: nums = [1,2,3,4]
* Output: 0
* Example 3:
*
* Input: nums = [1]
* Output: 0
*
*
* Constraints:
*
* 1 <= nums.length <= 104
* -105 <= nums[i] <= 105
*/
publicclassShortestUnsortedContiguousSubarray {
publicstaticintfindUnsortedSubarray(int[] nums) {
intmin = Integer.MAX_VALUE;
intmax = Integer.MIN_VALUE;
intleft = 0;
intright = 0;
booleanflag = false;
// Scan from left to find the starting point of the unsorted portion
for(inti = 1; i < nums.length; i++) {
if(nums[i] < nums[i - 1])
flag = true;
if (flag) { // find the minimum in the unsorted range
min = Math.min(min, nums[i]);
}
}
// Reset the flag
flag = false;
// Scan from right to find the ending point of the unsorted portion
for(inti = nums.length - 2; i >= 0; i--) {
if(nums[i] > nums[i + 1])
flag = true;
if(flag) { // find the maximum in the unsorted range
max = Math.max(max, nums[i]);
}
}
// Now we need the left and right index from where the sorting criteria is violated
for(left = 0; left < nums.length; left++) {
if (nums[left] > min) // leftmost point found
break;
}
for(right = nums.length - 1; right >= 0; right--) {
if(nums[right] < max) // rightmost point found
break;
}
returnright - left < 0 ? 0: right - left + 1;
}
publicstaticvoidmain(String[] args) {
int[] nums = newint[]{1, 3, 4, 7, 6, 2, 12, 10, 9, 11};
System.out.println(findUnsortedSubarray(nums));
}
}