-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add DifferenceArray.java, update readme
- Loading branch information
Showing
2 changed files
with
46 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
45 changes: 45 additions & 0 deletions
45
leetcode_java/src/main/java/AlgorithmJava/DifferenceArray.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |