Corporate Flight Bookings LeetCode solution in Java

1
class Solution {
2
public int[] corpFlightBookings(int[][] bookings, int n) {
3
// nums all equals to zero
4
int[] nums = new int[n];
5
// construct the diffs
6
Difference df = new Difference(nums);
7

8
for (int[] booking : bookings) {
9
// pay attention to the index
10
int i = booking[0] - 1;
11
int j = booking[1] - 1;
12
int val = booking[2];
13
// increase nums[i..j] by val
14
df.increment(i, j, val);
15
}
16
// return the final array
17
return df.result();
18
}
19

20
class Difference {
21
// diff array
22
private int[] diff;
23

24
public Difference(int[] nums) {
25
assert nums.length > 0;
26
diff = new int[nums.length];
27
// construct the diffs
28
diff[0] = nums[0];
29
for (int i = 1; i < nums.length; i++) {
30
diff[i] = nums[i] - nums[i - 1];
31
}
32
}
33

34
// increase nums[i..j] by val
35
public void increment(int i, int j, int val) {
36
diff[i] += val;
37
if (j + 1 < diff.length) {
38
diff[j + 1] -= val;
39
}
40
}
41

42
public int[] result() {
43
int[] res = new int[diff.length];
44
// contract the diff array based on the result
45
res[0] = diff[0];
46
for (int i = 1; i < diff.length; i++) {
47
res[i] = res[i - 1] + diff[i];
48
}
49
return res;
50
}
51
}
52
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0