-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubArrayProblem.java
More file actions
116 lines (83 loc) · 1.75 KB
/
Copy pathSubArrayProblem.java
File metadata and controls
116 lines (83 loc) · 1.75 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import java.util.*;
public class SubArrayProblem{
private LinkedList<Integer> maxList;
private LinkedList<Integer> minList;
private int[] arr;
private int value;
public SubArrayProblem(int[] _arr,int num){
maxList = new LinkedList<Integer>();
minList = new LinkedList<Integer>();
arr = _arr;
value = num;
}
//缩小,L++
public void shrinkWindow(int index){
while(!maxList.isEmpty()){
if(maxList.peekFirst() > index){
break;
}
maxList.removeFirst();
}
while(!minList.isEmpty()){
if(minList.peekFirst() > index){
break;
}
minList.removeFirst();
}
}
//扩大,R++
public void magnifyWindow(int index){
if(maxList.isEmpty()){
maxList.offerLast(index);
}else{
while(!maxList.isEmpty()){
if(arr[maxList.peekLast()]>arr[index]){
break;
}
maxList.removeLast();
}
maxList.offerLast(index);
}
if(minList.isEmpty()){
minList.offerLast(index);
}else{
while(!minList.isEmpty()){
if(arr[minList.peekLast()]<arr[index]){
break;
}
minList.removeLast();
}
minList.offerLast(index);
}
}
public int getMax(){
return arr[maxList.peekFirst()];
}
public int getMin(){
return arr[minList.peekFirst()];
}
public boolean isOK(){
return (getMax() - getMin()) <= value;
}
public void clear(){
maxList.clear();
minList.clear();
}
public int getSubArrayCount(){
int ways=0;
for (int i=0; i<arr.length; i++) {
clear();
for (int j=i; j<arr.length; j++) {
magnifyWindow(j);
ways+= isOK()?1:0;
}
}
return ways;
}
public static void main(String[] args){
int[] arr= new int[]{1,3,6,2};
int num = 4;
SubArrayProblem subArray=new SubArrayProblem(arr,num);
System.out.println("ways = "+subArray.getSubArrayCount());
}
}