From 36bc9bf565012c31bf8f2511d28db528d8830cce Mon Sep 17 00:00:00 2001 From: yennanliu Date: Sat, 21 Dec 2024 16:59:18 +0800 Subject: [PATCH] add DifferenceArray.java, update readme --- README.md | 2 +- .../java/AlgorithmJava/DifferenceArray.java | 45 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 leetcode_java/src/main/java/AlgorithmJava/DifferenceArray.java diff --git a/README.md b/README.md index b336ede5..72fd28bb 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/leetcode_java/src/main/java/AlgorithmJava/DifferenceArray.java b/leetcode_java/src/main/java/AlgorithmJava/DifferenceArray.java new file mode 100644 index 00000000..dea875c0 --- /dev/null +++ b/leetcode_java/src/main/java/AlgorithmJava/DifferenceArray.java @@ -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); + } +}