-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain581.java
More file actions
92 lines (86 loc) · 2.33 KB
/
Main581.java
File metadata and controls
92 lines (86 loc) · 2.33 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
85
86
87
88
89
90
91
92
package HOT100;
import java.util.Arrays;
public class Main581 {
/**
* 一次遍历
* @param nums
* @return
*/
public static int findUnsortedSubarray(int[] nums) {
int length = nums.length;
int endIndex = -1, maxValue = nums[0];
for (int i = 0; i < length; i++) {
if(nums[i] < maxValue) {
endIndex = i;
} else {
maxValue = nums[i];
}
}
int startIndex = -1, minValue = nums[length - 1];
for (int i = length - 1; i >= 0; i--) {
if(nums[i] > minValue) {
startIndex = i;
} else {
minValue = nums[i];
}
}
return endIndex == -1 ? 0 : endIndex - startIndex + 1;
}
/**
* 一次遍历优化
* @param nums
* @return
*/
public int findUnsortedSubarray1(int[] nums) {
int n = nums.length;
int maxValue = Integer.MIN_VALUE, right = -1;
int minValue = Integer.MAX_VALUE, left = -1;
for (int i = 0; i < n; i++) {
if(maxValue > nums[i]) {
right = i;
} else {
maxValue = nums[i];
}
if(minValue < nums[n - i - 1]) {
left = n - i - 1;
} else {
minValue = nums[n - i - 1];
}
}
return right == -1 ? 0 : right - left + 1;
}
/**
* 排序
* @param nums
* @return
*/
public int findUnsortedSubarray2(int[] nums) {
if(isSorted(nums)) {
return 0;
}
int[] numsSorted = new int[nums.length];
System.arraycopy(nums, 0, numsSorted, 0, nums.length);
Arrays.sort(numsSorted);
int left = 0;
while (nums[left] == numsSorted[left]) {
left++;
}
int right = nums.length - 1;
while (nums[right] == numsSorted[right]) {
right--;
}
return right - left + 1;
}
private boolean isSorted(int[] nums) {
for (int i = 1; i < nums.length; i++) {
if(nums[i] < nums[i - 1]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int[] nums = new int[]{1, 3, 2, 2, 2};
findUnsortedSubarray(nums);
}
}