Skip to content

Commit 36bc9bf

Browse files
committed
add DifferenceArray.java, update readme
1 parent 996d61d commit 36bc9bf

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@
199199
||Priority Queue (`unsorted`) | [Java](./algorithm/java/UnorderedMaxPQ.java) || | | AGAIN|
200200
||LRU cache | [Python](./algorithm/python/lru_cache.py) || LC 146 | | | AGAIN|
201201
||LFU Cache | [Python](./algorithm/python/lfu_cache.py) || LC 460 | | | AGAIN|
202-
202+
||DifferenceArray | [Java](./algorithm/java/DifferenceArray.java) || LC 1109, 370 | | | AGAIN|
203203

204204
## Array
205205

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package AlgorithmJava;
2+
3+
// https://github.com/yennanliu/CS_basics/blob/master/doc/cheatsheet/difference_array.md
4+
5+
import java.util.Arrays;
6+
7+
public class DifferenceArray {
8+
9+
// attr
10+
int[] array;
11+
12+
// method
13+
public int[] getDifferenceArray(int[][] input, int n) {
14+
15+
/** LC 1109. Corporate Flight Bookings input : [start, end, seats]
16+
*
17+
* NOTE !!!
18+
*
19+
* in java, index start from 0;
20+
* but in LC 1109, index start from 1
21+
*
22+
*/
23+
int[] tmp = new int[n + 1];
24+
for (int[] x : input) {
25+
int start = x[0];
26+
int end = x[1];
27+
int seats = x[2];
28+
29+
// add
30+
tmp[start] += seats;
31+
32+
// subtract
33+
if (end + 1 <= n) {
34+
tmp[end + 1] -= seats;
35+
}
36+
}
37+
38+
for (int i = 1; i < tmp.length; i++) {
39+
//tmp[i] = tmp[i - 1] + tmp[i];
40+
tmp[i] += tmp[i - 1];
41+
}
42+
43+
return Arrays.copyOfRange(tmp, 1, n+1);
44+
}
45+
}

0 commit comments

Comments
 (0)