FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/PuzzleCoding/src/MaxInWindow.java at master · wodgithub/algorithm · GitHub
wodgithub
algorithm
Repository navigation
Code
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
PuzzleCoding
/
src
/
MaxInWindow.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
50 lines (41 loc) · 1.59 KB
Breadcrumbs
algorithm
/
PuzzleCoding
/
src
/
MaxInWindow.java
Copy path
File metadata and controls
50 lines (41 loc) · 1.59 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import
java
.
util
.
ArrayList
;
import
java
.
util
.
LinkedList
;
import
java
.
util
.
Queue
;
/**
* Given an array of numbers and a sliding window size,
* how to get the maximal numbers in all sliding windows?
* <p/>
* For example, if the input array is {2, 3, 4, 2, 6, 2, 5, 1}
* and the size of sliding windows is 3,
* the output of maximums are {4, 4, 6, 6, 6, 5}
*/
public
class
MaxInWindow
{
public
static
void
main
(
String
[]
args
) {
int
[]
a
=
new
int
[]{
2
,
3
,
4
,
2
,
6
,
2
,
5
,
1
};
int
window
=
3
;
ArrayList
<
Integer
>
result
=
maxInWindow
(
a
,
window
);
System
.
out
.
println
(
result
.
toString
());
}
public
static
ArrayList
<
Integer
>
maxInWindow
(
int
[]
a
,
int
windowSize
) {
ArrayList
<
Integer
>
result
=
new
ArrayList
<
Integer
>();
Queue
<
Integer
>
maxIndexQueue
=
new
LinkedList
<
Integer
>();
if
(
a
.
length
>=
windowSize
&&
windowSize
>
1
) {
int
i
=
0
;
for
(;
i
<
windowSize
;
i
++) {
while
(!
maxIndexQueue
.
isEmpty
() &&
a
[
i
] >=
a
[
maxIndexQueue
.
peek
()])
maxIndexQueue
.
poll
();
maxIndexQueue
.
add
(
i
);
}
for
(;
i
<
a
.
length
;
i
++) {
result
.
add
(
a
[
maxIndexQueue
.
peek
()]);
while
(!
maxIndexQueue
.
isEmpty
() &&
a
[
i
] >=
a
[
maxIndexQueue
.
peek
()])
maxIndexQueue
.
poll
();
while
(!
maxIndexQueue
.
isEmpty
() &&
maxIndexQueue
.
peek
() <=
i
-
windowSize
)
maxIndexQueue
.
poll
();
maxIndexQueue
.
add
(
i
);
}
result
.
add
(
maxIndexQueue
.
peek
());
}
return
result
;
}
}
Back
|
FazBrowse Home
|
New Git URL