Skip to content

Commit 11aec5a

Browse files
committed
max number in sliding window
1 parent 9e67aba commit 11aec5a

2 files changed

Lines changed: 75 additions & 0 deletions

File tree

MathOps/src/MathOps.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,12 +79,37 @@ public static int divide(int dividend, int divisor) {
7979

8080
}
8181

82+
public static int divide1(int dividend, int divisor) {
83+
assert (divisor != 0);
84+
85+
boolean bNeg = false;
86+
if ((dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0))
87+
bNeg = true;
88+
long la = dividend;
89+
long ula = la < 0 ? -la : la;
90+
long lb = divisor;
91+
long ulb = lb < 0 ? -lb : lb;
92+
93+
int msb = 0;
94+
while ((ulb << msb) < ula) msb++;
95+
96+
int q = 0;
97+
for (int i = msb; i >= 0; i--) {
98+
if ((ulb << i) > ula) continue;
99+
q |= (1 << i);
100+
ula -= (ulb << i);
101+
}
102+
return bNeg ? -q : q;
103+
}
104+
82105
public static void main(String[] args) {
83106

84107
System.out.println("add: " + add(6, -2));
85108
System.out.println("sqrt: " + sqrt(120.0));
86109
System.out.println("pow: " + pow(2.0, -3));
87110
System.out.println("divide: " + divide(-21474, 3));
111+
System.out.println("divide: " + divide1(-10, 3));
112+
88113

89114
}
90115
}

PuzzleCoding/src/MaxInWindow.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import java.util.ArrayList;
2+
import java.util.LinkedList;
3+
import java.util.Queue;
4+
5+
/**
6+
* Given an array of numbers and a sliding window size,
7+
* how to get the maximal numbers in all sliding windows?
8+
* <p/>
9+
* For example, if the input array is {2, 3, 4, 2, 6, 2, 5, 1}
10+
* and the size of sliding windows is 3,
11+
* the output of maximums are {4, 4, 6, 6, 6, 5}
12+
*/
13+
public class MaxInWindow {
14+
public static void main(String[] args) {
15+
int[] a = new int[]{2, 3, 4, 2, 6, 2, 5, 1};
16+
int window = 3;
17+
ArrayList<Integer> result = maxInWindow(a, window);
18+
System.out.println(result.toString());
19+
}
20+
21+
public static ArrayList<Integer> maxInWindow(int[] a, int windowSize) {
22+
ArrayList<Integer> result = new ArrayList<Integer>();
23+
Queue<Integer> maxIndexQueue = new LinkedList<Integer>();
24+
25+
if (a.length >= windowSize && windowSize > 1) {
26+
int i = 0;
27+
for (; i < windowSize; i++) {
28+
while (!maxIndexQueue.isEmpty() && a[i] >= a[maxIndexQueue.peek()])
29+
maxIndexQueue.poll();
30+
31+
maxIndexQueue.add(i);
32+
}
33+
34+
for (; i < a.length; i++) {
35+
result.add(a[maxIndexQueue.peek()]);
36+
37+
while (!maxIndexQueue.isEmpty() && a[i] >= a[maxIndexQueue.peek()])
38+
maxIndexQueue.poll();
39+
40+
while (!maxIndexQueue.isEmpty() && maxIndexQueue.peek() <= i - windowSize)
41+
maxIndexQueue.poll();
42+
43+
maxIndexQueue.add(i);
44+
}
45+
result.add(maxIndexQueue.peek());
46+
}
47+
48+
return result;
49+
}
50+
}

0 commit comments

Comments
 (0)