Skip to content

Commit

Permalink
add DifferenceArray.java, update readme
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Dec 21, 2024
1 parent 996d61d commit 36bc9bf
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@
||Priority Queue (`unsorted`) | [Java](./algorithm/java/UnorderedMaxPQ.java) || | | AGAIN|
||LRU cache | [Python](./algorithm/python/lru_cache.py) || LC 146 | | | AGAIN|
||LFU Cache | [Python](./algorithm/python/lfu_cache.py) || LC 460 | | | AGAIN|

||DifferenceArray | [Java](./algorithm/java/DifferenceArray.java) || LC 1109, 370 | | | AGAIN|

## Array

Expand Down
45 changes: 45 additions & 0 deletions leetcode_java/src/main/java/AlgorithmJava/DifferenceArray.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package AlgorithmJava;

// https://github.com/yennanliu/CS_basics/blob/master/doc/cheatsheet/difference_array.md

import java.util.Arrays;

public class DifferenceArray {

// attr
int[] array;

// method
public int[] getDifferenceArray(int[][] input, int n) {

/** LC 1109. Corporate Flight Bookings input : [start, end, seats]
*
* NOTE !!!
*
* in java, index start from 0;
* but in LC 1109, index start from 1
*
*/
int[] tmp = new int[n + 1];
for (int[] x : input) {
int start = x[0];
int end = x[1];
int seats = x[2];

// add
tmp[start] += seats;

// subtract
if (end + 1 <= n) {
tmp[end + 1] -= seats;
}
}

for (int i = 1; i < tmp.length; i++) {
//tmp[i] = tmp[i - 1] + tmp[i];
tmp[i] += tmp[i - 1];
}

return Arrays.copyOfRange(tmp, 1, n+1);
}
}

0 comments on commit 36bc9bf

Please sign in to comment.