diff --git a/lcci/17.08.Circus Tower/README.md b/lcci/17.08.Circus Tower/README.md index 603078accf409..b7b0305299ebd 100644 --- a/lcci/17.08.Circus Tower/README.md +++ b/lcci/17.08.Circus Tower/README.md @@ -105,7 +105,7 @@ class Solution { int n = height.length; int[][] arr = new int[n][2]; for (int i = 0; i < n; ++i) { - arr[i] = new int[]{height[i], weight[i]}; + arr[i] = new int[] {height[i], weight[i]}; } Arrays.sort(arr, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); Set s = new HashSet<>(); diff --git a/lcci/17.08.Circus Tower/README_EN.md b/lcci/17.08.Circus Tower/README_EN.md index 1a905564cae6e..d37c7b5fa77d2 100644 --- a/lcci/17.08.Circus Tower/README_EN.md +++ b/lcci/17.08.Circus Tower/README_EN.md @@ -94,7 +94,7 @@ class Solution { int n = height.length; int[][] arr = new int[n][2]; for (int i = 0; i < n; ++i) { - arr[i] = new int[]{height[i], weight[i]}; + arr[i] = new int[] {height[i], weight[i]}; } Arrays.sort(arr, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); Set s = new HashSet<>(); diff --git a/lcci/17.08.Circus Tower/Solution.java b/lcci/17.08.Circus Tower/Solution.java index ef5b2ae72ac5e..57af761130930 100644 --- a/lcci/17.08.Circus Tower/Solution.java +++ b/lcci/17.08.Circus Tower/Solution.java @@ -29,7 +29,7 @@ public int bestSeqAtIndex(int[] height, int[] weight) { int n = height.length; int[][] arr = new int[n][2]; for (int i = 0; i < n; ++i) { - arr[i] = new int[]{height[i], weight[i]}; + arr[i] = new int[] {height[i], weight[i]}; } Arrays.sort(arr, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]); Set s = new HashSet<>(); diff --git a/solution/0400-0499/0480.Sliding Window Median/README.md b/solution/0400-0499/0480.Sliding Window Median/README.md index 7691e48263217..c7eb37d29070f 100644 --- a/solution/0400-0499/0480.Sliding Window Median/README.md +++ b/solution/0400-0499/0480.Sliding Window Median/README.md @@ -219,7 +219,6 @@ class MedianFinder { } } - class Solution { public double[] medianSlidingWindow(int[] nums, int k) { MedianFinder finder = new MedianFinder(k); diff --git a/solution/0400-0499/0480.Sliding Window Median/README_EN.md b/solution/0400-0499/0480.Sliding Window Median/README_EN.md index d73bcb21eae5e..65de217c59583 100644 --- a/solution/0400-0499/0480.Sliding Window Median/README_EN.md +++ b/solution/0400-0499/0480.Sliding Window Median/README_EN.md @@ -191,7 +191,6 @@ class MedianFinder { } } - class Solution { public double[] medianSlidingWindow(int[] nums, int k) { MedianFinder finder = new MedianFinder(k); diff --git a/solution/0400-0499/0480.Sliding Window Median/Solution.cpp b/solution/0400-0499/0480.Sliding Window Median/Solution.cpp index 57cb079e4f269..fc555951ad493 100644 --- a/solution/0400-0499/0480.Sliding Window Median/Solution.cpp +++ b/solution/0400-0499/0480.Sliding Window Median/Solution.cpp @@ -43,7 +43,7 @@ class MedianFinder { int largeSize = 0; int k; - template + template void prune(T& pq) { while (!pq.empty() && delayed[pq.top()]) { if (--delayed[pq.top()] == 0) { diff --git a/solution/0400-0499/0480.Sliding Window Median/Solution.java b/solution/0400-0499/0480.Sliding Window Median/Solution.java index 5abd0ca8444c9..b40ecc80faacc 100644 --- a/solution/0400-0499/0480.Sliding Window Median/Solution.java +++ b/solution/0400-0499/0480.Sliding Window Median/Solution.java @@ -65,7 +65,6 @@ private void rebalance() { } } - class Solution { public double[] medianSlidingWindow(int[] nums, int k) { MedianFinder finder = new MedianFinder(k); diff --git a/solution/0500-0599/0514.Freedom Trail/README.md b/solution/0500-0599/0514.Freedom Trail/README.md index 38af7db7bc6c7..5c89a2c244a19 100644 --- a/solution/0500-0599/0514.Freedom Trail/README.md +++ b/solution/0500-0599/0514.Freedom Trail/README.md @@ -121,7 +121,8 @@ class Solution { for (int i = 1; i < m; ++i) { for (int j : pos[key.charAt(i) - 'a']) { for (int k : pos[key.charAt(i - 1) - 'a']) { - f[i][j] = Math.min(f[i][j], f[i - 1][k] + Math.min(Math.abs(j - k), n - Math.abs(j - k)) + 1); + f[i][j] = Math.min( + f[i][j], f[i - 1][k] + Math.min(Math.abs(j - k), n - Math.abs(j - k)) + 1); } } } diff --git a/solution/0500-0599/0514.Freedom Trail/README_EN.md b/solution/0500-0599/0514.Freedom Trail/README_EN.md index 4669e1e853bf6..1a61291ab7295 100644 --- a/solution/0500-0599/0514.Freedom Trail/README_EN.md +++ b/solution/0500-0599/0514.Freedom Trail/README_EN.md @@ -93,7 +93,8 @@ class Solution { for (int i = 1; i < m; ++i) { for (int j : pos[key.charAt(i) - 'a']) { for (int k : pos[key.charAt(i - 1) - 'a']) { - f[i][j] = Math.min(f[i][j], f[i - 1][k] + Math.min(Math.abs(j - k), n - Math.abs(j - k)) + 1); + f[i][j] = Math.min( + f[i][j], f[i - 1][k] + Math.min(Math.abs(j - k), n - Math.abs(j - k)) + 1); } } } diff --git a/solution/0500-0599/0514.Freedom Trail/Solution.cpp b/solution/0500-0599/0514.Freedom Trail/Solution.cpp index 1dedbac0f5102..332b9eed36ad4 100644 --- a/solution/0500-0599/0514.Freedom Trail/Solution.cpp +++ b/solution/0500-0599/0514.Freedom Trail/Solution.cpp @@ -14,7 +14,7 @@ class Solution { for (int i = 1; i < m; ++i) { for (int j : pos[key[i] - 'a']) { for (int k : pos[key[i - 1] - 'a']) { - f[i][j] = min(f[i][j], f[i - 1][k] + min(abs(j - k), n - abs(j - k)) + 1); + f[i][j] = min(f[i][j], f[i - 1][k] + min(abs(j - k), n - abs(j - k)) + 1); } } } diff --git a/solution/0500-0599/0514.Freedom Trail/Solution.java b/solution/0500-0599/0514.Freedom Trail/Solution.java index 07e0e3571528c..2acf21a987f8f 100644 --- a/solution/0500-0599/0514.Freedom Trail/Solution.java +++ b/solution/0500-0599/0514.Freedom Trail/Solution.java @@ -17,7 +17,8 @@ public int findRotateSteps(String ring, String key) { for (int i = 1; i < m; ++i) { for (int j : pos[key.charAt(i) - 'a']) { for (int k : pos[key.charAt(i - 1) - 'a']) { - f[i][j] = Math.min(f[i][j], f[i - 1][k] + Math.min(Math.abs(j - k), n - Math.abs(j - k)) + 1); + f[i][j] = Math.min( + f[i][j], f[i - 1][k] + Math.min(Math.abs(j - k), n - Math.abs(j - k)) + 1); } } } diff --git a/solution/0600-0699/0665.Non-decreasing Array/Solution.java b/solution/0600-0699/0665.Non-decreasing Array/Solution.java index fb62427c16beb..d16b9742aaf4c 100644 --- a/solution/0600-0699/0665.Non-decreasing Array/Solution.java +++ b/solution/0600-0699/0665.Non-decreasing Array/Solution.java @@ -14,7 +14,7 @@ public boolean checkPossibility(int[] nums) { } return true; } - + private boolean isSorted(int[] nums) { for (int i = 0; i < nums.length - 1; ++i) { if (nums[i] > nums[i + 1]) { diff --git a/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README.md b/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README.md index ac7c8be0cdf10..5ff9be63e4aea 100644 --- a/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README.md +++ b/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README.md @@ -127,7 +127,8 @@ class Solution { break; } x = x * 10 + num.charAt(j) - '0'; - if (x > Integer.MAX_VALUE || (ans.size() >= 2 && x > ans.get(ans.size() - 1) + ans.get(ans.size() - 2))) { + if (x > Integer.MAX_VALUE + || (ans.size() >= 2 && x > ans.get(ans.size() - 1) + ans.get(ans.size() - 2))) { break; } if (ans.size() < 2 || x == ans.get(ans.size() - 1) + ans.get(ans.size() - 2)) { diff --git a/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README_EN.md b/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README_EN.md index c9ae427b91e11..22cf85eeb7517 100644 --- a/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README_EN.md +++ b/solution/0800-0899/0842.Split Array into Fibonacci Sequence/README_EN.md @@ -106,7 +106,8 @@ class Solution { break; } x = x * 10 + num.charAt(j) - '0'; - if (x > Integer.MAX_VALUE || (ans.size() >= 2 && x > ans.get(ans.size() - 1) + ans.get(ans.size() - 2))) { + if (x > Integer.MAX_VALUE + || (ans.size() >= 2 && x > ans.get(ans.size() - 1) + ans.get(ans.size() - 2))) { break; } if (ans.size() < 2 || x == ans.get(ans.size() - 1) + ans.get(ans.size() - 2)) { diff --git a/solution/0800-0899/0842.Split Array into Fibonacci Sequence/Solution.java b/solution/0800-0899/0842.Split Array into Fibonacci Sequence/Solution.java index cd9f12a84ec47..23bbd7beea12d 100644 --- a/solution/0800-0899/0842.Split Array into Fibonacci Sequence/Solution.java +++ b/solution/0800-0899/0842.Split Array into Fibonacci Sequence/Solution.java @@ -18,7 +18,8 @@ private boolean dfs(int i) { break; } x = x * 10 + num.charAt(j) - '0'; - if (x > Integer.MAX_VALUE || (ans.size() >= 2 && x > ans.get(ans.size() - 1) + ans.get(ans.size() - 2))) { + if (x > Integer.MAX_VALUE + || (ans.size() >= 2 && x > ans.get(ans.size() - 1) + ans.get(ans.size() - 2))) { break; } if (ans.size() < 2 || x == ans.get(ans.size() - 1) + ans.get(ans.size() - 2)) { diff --git a/solution/0800-0899/0879.Profitable Schemes/README.md b/solution/0800-0899/0879.Profitable Schemes/README.md index 6a50ab73775d3..60cce2ede49db 100644 --- a/solution/0800-0899/0879.Profitable Schemes/README.md +++ b/solution/0800-0899/0879.Profitable Schemes/README.md @@ -106,7 +106,10 @@ class Solution { for (int k = 0; k <= minProfit; ++k) { f[i][j][k] = f[i - 1][j][k]; if (j >= group[i - 1]) { - f[i][j][k] = (f[i][j][k] + f[i - 1][j - group[i - 1]][Math.max(0, k - profit[i - 1])]) % mod; + f[i][j][k] + = (f[i][j][k] + + f[i - 1][j - group[i - 1]][Math.max(0, k - profit[i - 1])]) + % mod; } } } diff --git a/solution/0800-0899/0879.Profitable Schemes/README_EN.md b/solution/0800-0899/0879.Profitable Schemes/README_EN.md index 9da823565c47a..76095bfc84466 100644 --- a/solution/0800-0899/0879.Profitable Schemes/README_EN.md +++ b/solution/0800-0899/0879.Profitable Schemes/README_EN.md @@ -80,7 +80,10 @@ class Solution { for (int k = 0; k <= minProfit; ++k) { f[i][j][k] = f[i - 1][j][k]; if (j >= group[i - 1]) { - f[i][j][k] = (f[i][j][k] + f[i - 1][j - group[i - 1]][Math.max(0, k - profit[i - 1])]) % mod; + f[i][j][k] + = (f[i][j][k] + + f[i - 1][j - group[i - 1]][Math.max(0, k - profit[i - 1])]) + % mod; } } } diff --git a/solution/0800-0899/0879.Profitable Schemes/Solution.java b/solution/0800-0899/0879.Profitable Schemes/Solution.java index 2296054d06fb2..f95d3af71bda6 100644 --- a/solution/0800-0899/0879.Profitable Schemes/Solution.java +++ b/solution/0800-0899/0879.Profitable Schemes/Solution.java @@ -11,7 +11,10 @@ public int profitableSchemes(int n, int minProfit, int[] group, int[] profit) { for (int k = 0; k <= minProfit; ++k) { f[i][j][k] = f[i - 1][j][k]; if (j >= group[i - 1]) { - f[i][j][k] = (f[i][j][k] + f[i - 1][j - group[i - 1]][Math.max(0, k - profit[i - 1])]) % mod; + f[i][j][k] + = (f[i][j][k] + + f[i - 1][j - group[i - 1]][Math.max(0, k - profit[i - 1])]) + % mod; } } } diff --git a/solution/1000-1099/1000.Minimum Cost to Merge Stones/README.md b/solution/1000-1099/1000.Minimum Cost to Merge Stones/README.md index d0b0f90bdecfe..856b0d42a4df7 100644 --- a/solution/1000-1099/1000.Minimum Cost to Merge Stones/README.md +++ b/solution/1000-1099/1000.Minimum Cost to Merge Stones/README.md @@ -122,7 +122,7 @@ class Solution { int[][][] f = new int[n + 1][n + 1][K + 1]; final int inf = 1 << 20; for (int[][] g : f) { - for(int[] e : g) { + for (int[] e : g) { Arrays.fill(e, inf); } } diff --git a/solution/1000-1099/1000.Minimum Cost to Merge Stones/README_EN.md b/solution/1000-1099/1000.Minimum Cost to Merge Stones/README_EN.md index 99e4844297c86..9e9fb00e7dc1a 100644 --- a/solution/1000-1099/1000.Minimum Cost to Merge Stones/README_EN.md +++ b/solution/1000-1099/1000.Minimum Cost to Merge Stones/README_EN.md @@ -94,7 +94,7 @@ class Solution { int[][][] f = new int[n + 1][n + 1][K + 1]; final int inf = 1 << 20; for (int[][] g : f) { - for(int[] e : g) { + for (int[] e : g) { Arrays.fill(e, inf); } } diff --git a/solution/1000-1099/1000.Minimum Cost to Merge Stones/Solution.java b/solution/1000-1099/1000.Minimum Cost to Merge Stones/Solution.java index 39416f6fa799d..cbbc600375bb3 100644 --- a/solution/1000-1099/1000.Minimum Cost to Merge Stones/Solution.java +++ b/solution/1000-1099/1000.Minimum Cost to Merge Stones/Solution.java @@ -11,7 +11,7 @@ public int mergeStones(int[] stones, int K) { int[][][] f = new int[n + 1][n + 1][K + 1]; final int inf = 1 << 20; for (int[][] g : f) { - for(int[] e : g) { + for (int[] e : g) { Arrays.fill(e, inf); } } diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/README.md b/solution/1000-1099/1030.Matrix Cells in Distance Order/README.md index c0daadcdf19a8..71de61e650fff 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/README.md +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/README.md @@ -99,7 +99,7 @@ import java.util.Deque; class Solution { public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { Deque q = new ArrayDeque<>(); - q.offer(new int[]{rCenter, cCenter}); + q.offer(new int[] {rCenter, cCenter}); boolean[][] vis = new boolean[rows][cols]; vis[rCenter][cCenter] = true; int[][] ans = new int[rows * cols][2]; @@ -113,7 +113,7 @@ class Solution { int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { vis[x][y] = true; - q.offer(new int[]{x, y}); + q.offer(new int[] {x, y}); } } } diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md b/solution/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md index 00a4f3fdae8be..c5c5b04be94f1 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/README_EN.md @@ -81,7 +81,7 @@ import java.util.Deque; class Solution { public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { Deque q = new ArrayDeque<>(); - q.offer(new int[]{rCenter, cCenter}); + q.offer(new int[] {rCenter, cCenter}); boolean[][] vis = new boolean[rows][cols]; vis[rCenter][cCenter] = true; int[][] ans = new int[rows * cols][2]; @@ -95,7 +95,7 @@ class Solution { int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { vis[x][y] = true; - q.offer(new int[]{x, y}); + q.offer(new int[] {x, y}); } } } diff --git a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.java b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.java index 0b7cefe96c6f6..d74244896f041 100644 --- a/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.java +++ b/solution/1000-1099/1030.Matrix Cells in Distance Order/Solution.java @@ -3,7 +3,7 @@ class Solution { public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { Deque q = new ArrayDeque<>(); - q.offer(new int[]{rCenter, cCenter}); + q.offer(new int[] {rCenter, cCenter}); boolean[][] vis = new boolean[rows][cols]; vis[rCenter][cCenter] = true; int[][] ans = new int[rows * cols][2]; @@ -17,7 +17,7 @@ public int[][] allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) { int x = p[0] + dirs[k], y = p[1] + dirs[k + 1]; if (x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y]) { vis[x][y] = true; - q.offer(new int[]{x, y}); + q.offer(new int[] {x, y}); } } } diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md b/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md index 817bfba199be1..025c49d78f3dc 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/README.md @@ -92,7 +92,7 @@ class Solution { mi = y - x < 3 || z - y < 3 ? 1 : 2; mx = z - x - 2; } - return new int[]{mi, mx}; + return new int[] {mi, mx}; } } ``` diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md b/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md index 11c938fde70e8..0cfff63bd2502 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/README_EN.md @@ -81,7 +81,7 @@ class Solution { mi = y - x < 3 || z - y < 3 ? 1 : 2; mx = z - x - 2; } - return new int[]{mi, mx}; + return new int[] {mi, mx}; } } ``` diff --git a/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.java b/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.java index 5f87b1e36a902..9e164c3022f63 100644 --- a/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.java +++ b/solution/1000-1099/1033.Moving Stones Until Consecutive/Solution.java @@ -8,6 +8,6 @@ public int[] numMovesStones(int a, int b, int c) { mi = y - x < 3 || z - y < 3 ? 1 : 2; mx = z - x - 2; } - return new int[]{mi, mx}; + return new int[] {mi, mx}; } } \ No newline at end of file diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README.md b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README.md index c4b6baa1e9c19..b91a71d8104c0 100644 --- a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README.md +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README.md @@ -211,7 +211,8 @@ class Solution { int j = i + l - 1; f[i][j] = 1 << 30; for (int k = i + 1; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + f[i][j] + = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); } } } diff --git a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README_EN.md b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README_EN.md index 64696c2cba53c..3bb120638f719 100644 --- a/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README_EN.md +++ b/solution/1000-1099/1039.Minimum Score Triangulation of Polygon/README_EN.md @@ -145,7 +145,8 @@ class Solution { int j = i + l - 1; f[i][j] = 1 << 30; for (int k = i + 1; k < j; ++k) { - f[i][j] = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); + f[i][j] + = Math.min(f[i][j], f[i][k] + f[k][j] + values[i] * values[k] * values[j]); } } } diff --git a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution.java b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution.java index 05c5fd1d7388c..7d2d9425f3373 100644 --- a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution.java +++ b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/Solution.java @@ -1,6 +1,6 @@ class Solution { private int[] p; - + public int earliestAcq(int[][] logs, int n) { Arrays.sort(logs, (a, b) -> a[0] - b[0]); p = new int[n]; @@ -19,7 +19,7 @@ public int earliestAcq(int[][] logs, int n) { } return -1; } - + private int find(int x) { if (p[x] != x) { p[x] = find(p[x]); diff --git a/solution/1100-1199/1109.Corporate Flight Bookings/README.md b/solution/1100-1199/1109.Corporate Flight Bookings/README.md index 7f96f4392de6f..81b07d75d5e4e 100644 --- a/solution/1100-1199/1109.Corporate Flight Bookings/README.md +++ b/solution/1100-1199/1109.Corporate Flight Bookings/README.md @@ -151,7 +151,7 @@ class Solution { public int[] corpFlightBookings(int[][] bookings, int n) { BinaryIndexedTree tree = new BinaryIndexedTree(n); for (var e : bookings) { - int first =e[0], last = e[1], seats = e[2]; + int first = e[0], last = e[1], seats = e[2]; tree.update(first, seats); tree.update(last + 1, -seats); } diff --git a/solution/1100-1199/1109.Corporate Flight Bookings/README_EN.md b/solution/1100-1199/1109.Corporate Flight Bookings/README_EN.md index febc226ae04e6..0a41f4b33b5ab 100644 --- a/solution/1100-1199/1109.Corporate Flight Bookings/README_EN.md +++ b/solution/1100-1199/1109.Corporate Flight Bookings/README_EN.md @@ -121,7 +121,7 @@ class Solution { public int[] corpFlightBookings(int[][] bookings, int n) { BinaryIndexedTree tree = new BinaryIndexedTree(n); for (var e : bookings) { - int first =e[0], last = e[1], seats = e[2]; + int first = e[0], last = e[1], seats = e[2]; tree.update(first, seats); tree.update(last + 1, -seats); } diff --git a/solution/1300-1399/1301.Number of Paths with Max Score/README.md b/solution/1300-1399/1301.Number of Paths with Max Score/README.md index d93edae3fd650..941fded34eddb 100644 --- a/solution/1300-1399/1301.Number of Paths with Max Score/README.md +++ b/solution/1300-1399/1301.Number of Paths with Max Score/README.md @@ -138,7 +138,8 @@ class Solution { } private void update(int i, int j, int x, int y) { - if (x >= n || y >= n || f[x][y] == -1 || board.get(i).charAt(j) == 'X' || board.get(i).charAt(j) == 'S') { + if (x >= n || y >= n || f[x][y] == -1 || board.get(i).charAt(j) == 'X' + || board.get(i).charAt(j) == 'S') { return; } if (f[x][y] > f[i][j]) { diff --git a/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md b/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md index aaff671287206..3729253cba026 100644 --- a/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md +++ b/solution/1300-1399/1301.Number of Paths with Max Score/README_EN.md @@ -117,7 +117,8 @@ class Solution { } private void update(int i, int j, int x, int y) { - if (x >= n || y >= n || f[x][y] == -1 || board.get(i).charAt(j) == 'X' || board.get(i).charAt(j) == 'S') { + if (x >= n || y >= n || f[x][y] == -1 || board.get(i).charAt(j) == 'X' + || board.get(i).charAt(j) == 'S') { return; } if (f[x][y] > f[i][j]) { diff --git a/solution/1300-1399/1301.Number of Paths with Max Score/Solution.java b/solution/1300-1399/1301.Number of Paths with Max Score/Solution.java index 7191bd2ea6ec2..7bb4976c59a1f 100644 --- a/solution/1300-1399/1301.Number of Paths with Max Score/Solution.java +++ b/solution/1300-1399/1301.Number of Paths with Max Score/Solution.java @@ -37,7 +37,8 @@ public int[] pathsWithMaxScore(List board) { } private void update(int i, int j, int x, int y) { - if (x >= n || y >= n || f[x][y] == -1 || board.get(i).charAt(j) == 'X' || board.get(i).charAt(j) == 'S') { + if (x >= n || y >= n || f[x][y] == -1 || board.get(i).charAt(j) == 'X' + || board.get(i).charAt(j) == 'S') { return; } if (f[x][y] > f[i][j]) { diff --git a/solution/1300-1399/1338.Reduce Array Size to The Half/README.md b/solution/1300-1399/1338.Reduce Array Size to The Half/README.md index 0e7a69a0219fe..b0c2c87537626 100644 --- a/solution/1300-1399/1338.Reduce Array Size to The Half/README.md +++ b/solution/1300-1399/1338.Reduce Array Size to The Half/README.md @@ -87,7 +87,7 @@ class Solution { Arrays.sort(cnt); int ans = 0; int m = 0; - for (int i = mx; ; --i) { + for (int i = mx;; --i) { if (cnt[i] > 0) { m += cnt[i]; ++ans; diff --git a/solution/1300-1399/1338.Reduce Array Size to The Half/README_EN.md b/solution/1300-1399/1338.Reduce Array Size to The Half/README_EN.md index 921941fb3e74d..fc505c3b16bd1 100644 --- a/solution/1300-1399/1338.Reduce Array Size to The Half/README_EN.md +++ b/solution/1300-1399/1338.Reduce Array Size to The Half/README_EN.md @@ -71,7 +71,7 @@ class Solution { Arrays.sort(cnt); int ans = 0; int m = 0; - for (int i = mx; ; --i) { + for (int i = mx;; --i) { if (cnt[i] > 0) { m += cnt[i]; ++ans; diff --git a/solution/1300-1399/1338.Reduce Array Size to The Half/Solution.java b/solution/1300-1399/1338.Reduce Array Size to The Half/Solution.java index c6da44587c4b4..c33770c56878f 100644 --- a/solution/1300-1399/1338.Reduce Array Size to The Half/Solution.java +++ b/solution/1300-1399/1338.Reduce Array Size to The Half/Solution.java @@ -11,7 +11,7 @@ public int minSetSize(int[] arr) { Arrays.sort(cnt); int ans = 0; int m = 0; - for (int i = mx; ; --i) { + for (int i = mx;; --i) { if (cnt[i] > 0) { m += cnt[i]; ++ans; diff --git a/solution/1300-1399/1361.Validate Binary Tree Nodes/README.md b/solution/1300-1399/1361.Validate Binary Tree Nodes/README.md index 89c448dd1dbab..6d4c8bf92ff65 100644 --- a/solution/1300-1399/1361.Validate Binary Tree Nodes/README.md +++ b/solution/1300-1399/1361.Validate Binary Tree Nodes/README.md @@ -117,7 +117,7 @@ class Solution { p[i] = i; } boolean[] vis = new boolean[n]; - for (int i = 0, m = n; i < m; ++i) { + for (int i = 0, m = n; i < m; ++i) { for (int j : new int[] {leftChild[i], rightChild[i]}) { if (j != -1) { if (vis[j] || find(i) == find(j)) { diff --git a/solution/1300-1399/1361.Validate Binary Tree Nodes/README_EN.md b/solution/1300-1399/1361.Validate Binary Tree Nodes/README_EN.md index 9def38124da0e..5185b65e03129 100644 --- a/solution/1300-1399/1361.Validate Binary Tree Nodes/README_EN.md +++ b/solution/1300-1399/1361.Validate Binary Tree Nodes/README_EN.md @@ -84,7 +84,7 @@ class Solution { p[i] = i; } boolean[] vis = new boolean[n]; - for (int i = 0, m = n; i < m; ++i) { + for (int i = 0, m = n; i < m; ++i) { for (int j : new int[] {leftChild[i], rightChild[i]}) { if (j != -1) { if (vis[j] || find(i) == find(j)) { diff --git a/solution/1300-1399/1361.Validate Binary Tree Nodes/Solution.java b/solution/1300-1399/1361.Validate Binary Tree Nodes/Solution.java index fb7ff7f1bfd70..338221542de9f 100644 --- a/solution/1300-1399/1361.Validate Binary Tree Nodes/Solution.java +++ b/solution/1300-1399/1361.Validate Binary Tree Nodes/Solution.java @@ -7,7 +7,7 @@ public boolean validateBinaryTreeNodes(int n, int[] leftChild, int[] rightChild) p[i] = i; } boolean[] vis = new boolean[n]; - for (int i = 0, m = n; i < m; ++i) { + for (int i = 0, m = n; i < m; ++i) { for (int j : new int[] {leftChild[i], rightChild[i]}) { if (j != -1) { if (vis[j] || find(i) == find(j)) { diff --git a/solution/1400-1499/1406.Stone Game III/Solution.java b/solution/1400-1499/1406.Stone Game III/Solution.java index b06920890cca2..f48bc01caa1f0 100644 --- a/solution/1400-1499/1406.Stone Game III/Solution.java +++ b/solution/1400-1499/1406.Stone Game III/Solution.java @@ -2,7 +2,7 @@ class Solution { private int n; private int[] s; private Integer[] f; - + public String stoneGameIII(int[] stoneValue) { n = stoneValue.length; s = new int[n + 1]; @@ -14,7 +14,7 @@ public String stoneGameIII(int[] stoneValue) { int b = s[n] - a; return a == b ? "Tie" : a > b ? "Alice" : "Bob"; } - + private int dfs(int i) { if (i >= n) { return 0; diff --git a/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README.md b/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README.md index 948ac95175c9a..e81c19da03890 100644 --- a/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README.md +++ b/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README.md @@ -170,6 +170,716 @@ func max(a, b int) int { } ``` +### **TypeScript** + +````ts +function longestSubarray(nums: number[], limit: number): number { + const ts = new TreapMultiSet(); + let ans = 0; + let j = 0; + for (let i = 0; i < nums.length; ++i) { + ts.add(nums[i]); + while (ts.last() - ts.first() > limit) { + ts.delete(nums[j++]); + } + ans = Math.max(ans, i - j + 1); + } + return ans; +} + +type CompareFunction = ( + a: T, + b: T, +) => R extends 'number' ? number : boolean; + +interface ITreapMultiSet extends Iterable { + add: (...value: T[]) => this; + has: (value: T) => boolean; + delete: (value: T) => void; + + bisectLeft: (value: T) => number; + bisectRight: (value: T) => number; + + indexOf: (value: T) => number; + lastIndexOf: (value: T) => number; + + at: (index: number) => T | undefined; + first: () => T | undefined; + last: () => T | undefined; + + lower: (value: T) => T | undefined; + higher: (value: T) => T | undefined; + floor: (value: T) => T | undefined; + ceil: (value: T) => T | undefined; + + shift: () => T | undefined; + pop: (index?: number) => T | undefined; + + count: (value: T) => number; + + keys: () => IterableIterator; + values: () => IterableIterator; + rvalues: () => IterableIterator; + entries: () => IterableIterator<[number, T]>; + + readonly size: number; +} + +class TreapNode { + value: T; + count: number; + size: number; + priority: number; + left: TreapNode | null; + right: TreapNode | null; + + constructor(value: T) { + this.value = value; + this.count = 1; + this.size = 1; + this.priority = Math.random(); + this.left = null; + this.right = null; + } + + static getSize(node: TreapNode | null): number { + return node?.size ?? 0; + } + + static getFac(node: TreapNode | null): number { + return node?.priority ?? 0; + } + + pushUp(): void { + let tmp = this.count; + tmp += TreapNode.getSize(this.left); + tmp += TreapNode.getSize(this.right); + this.size = tmp; + } + + rotateRight(): TreapNode { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let node: TreapNode = this; + const left = node.left; + node.left = left?.right ?? null; + left && (left.right = node); + left && (node = left); + node.right?.pushUp(); + node.pushUp(); + return node; + } + + rotateLeft(): TreapNode { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let node: TreapNode = this; + const right = node.right; + node.right = right?.left ?? null; + right && (right.left = node); + right && (node = right); + node.left?.pushUp(); + node.pushUp(); + return node; + } +} + +class TreapMultiSet implements ITreapMultiSet { + private readonly root: TreapNode; + private readonly compareFn: CompareFunction; + private readonly leftBound: T; + private readonly rightBound: T; + + /** + * + * @param compareFn A compare function which returns boolean or number + * @param leftBound defalut value is `-Infinity` + * @param rightBound defalut value is `Infinity` + * @description + * create a `MultiSet`, compare elements using `compareFn`, which is increasing order by default. + * @example + * ```ts + * interface Person { + name: string + age: number + } + + const leftBound = { + name: 'Alice', + age: -Infinity, + } + + const rightBound = { + name: 'Bob', + age: Infinity, + } + + const sortedList = new TreapMultiSet( + (a: Person, b: Person) => a.age - b.age, + leftBound, + rightBound + ) + * ``` + */ + constructor(compareFn?: CompareFunction); + constructor( + compareFn: CompareFunction, + leftBound: T, + rightBound: T, + ); + constructor( + compareFn: CompareFunction = (a: any, b: any) => a - b, + leftBound: any = -Infinity, + rightBound: any = Infinity, + ) { + this.root = new TreapNode(rightBound); + this.root.priority = Infinity; + this.root.left = new TreapNode(leftBound); + this.root.left.priority = -Infinity; + this.root.pushUp(); + + this.leftBound = leftBound; + this.rightBound = rightBound; + this.compareFn = compareFn; + } + + get size(): number { + return this.root.size - 2; + } + + get height(): number { + const getHeight = (node: TreapNode | null): number => { + if (node == null) return 0; + return 1 + Math.max(getHeight(node.left), getHeight(node.right)); + }; + + return getHeight(this.root); + } + + /** + * + * @complexity `O(logn)` + * @description Returns true if value is a member. + */ + has(value: T): boolean { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): boolean => { + if (node == null) return false; + if (compare(node.value, value) === 0) return true; + if (compare(node.value, value) < 0) return dfs(node.right, value); + return dfs(node.left, value); + }; + + return dfs(this.root, value); + } + + /** + * + * @complexity `O(logn)` + * @description Add value to sorted set. + */ + add(...values: T[]): this { + const compare = this.compareFn; + const dfs = ( + node: TreapNode | null, + value: T, + parent: TreapNode, + direction: 'left' | 'right', + ): void => { + if (node == null) return; + if (compare(node.value, value) === 0) { + node.count++; + node.pushUp(); + } else if (compare(node.value, value) > 0) { + if (node.left) { + dfs(node.left, value, node, 'left'); + } else { + node.left = new TreapNode(value); + node.pushUp(); + } + + if (TreapNode.getFac(node.left) > node.priority) { + parent[direction] = node.rotateRight(); + } + } else if (compare(node.value, value) < 0) { + if (node.right) { + dfs(node.right, value, node, 'right'); + } else { + node.right = new TreapNode(value); + node.pushUp(); + } + + if (TreapNode.getFac(node.right) > node.priority) { + parent[direction] = node.rotateLeft(); + } + } + parent.pushUp(); + }; + + values.forEach(value => dfs(this.root.left, value, this.root, 'left')); + return this; + } + + /** + * + * @complexity `O(logn)` + * @description Remove value from sorted set if it is a member. + * If value is not a member, do nothing. + */ + delete(value: T): void { + const compare = this.compareFn; + const dfs = ( + node: TreapNode | null, + value: T, + parent: TreapNode, + direction: 'left' | 'right', + ): void => { + if (node == null) return; + + if (compare(node.value, value) === 0) { + if (node.count > 1) { + node.count--; + node?.pushUp(); + } else if (node.left == null && node.right == null) { + parent[direction] = null; + } else { + // 旋到根节点 + if ( + node.right == null || + TreapNode.getFac(node.left) > + TreapNode.getFac(node.right) + ) { + parent[direction] = node.rotateRight(); + dfs( + parent[direction]?.right ?? null, + value, + parent[direction]!, + 'right', + ); + } else { + parent[direction] = node.rotateLeft(); + dfs( + parent[direction]?.left ?? null, + value, + parent[direction]!, + 'left', + ); + } + } + } else if (compare(node.value, value) > 0) { + dfs(node.left, value, node, 'left'); + } else if (compare(node.value, value) < 0) { + dfs(node.right, value, node, 'right'); + } + + parent?.pushUp(); + }; + + dfs(this.root.left, value, this.root, 'left'); + } + + /** + * + * @complexity `O(logn)` + * @description Returns an index to insert value in the sorted set. + * If the value is already present, the insertion point will be before (to the left of) any existing values. + */ + bisectLeft(value: T): number { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + return TreapNode.getSize(node.left); + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return ( + dfs(node.right, value) + + TreapNode.getSize(node.left) + + node.count + ); + } + + return 0; + }; + + return dfs(this.root, value) - 1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns an index to insert value in the sorted set. + * If the value is already present, the insertion point will be before (to the right of) any existing values. + */ + bisectRight(value: T): number { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + return TreapNode.getSize(node.left) + node.count; + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return ( + dfs(node.right, value) + + TreapNode.getSize(node.left) + + node.count + ); + } + + return 0; + }; + return dfs(this.root, value) - 1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns the index of the first occurrence of a value in the set, or -1 if it is not present. + */ + indexOf(value: T): number { + const compare = this.compareFn; + let isExist = false; + + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + isExist = true; + return TreapNode.getSize(node.left); + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return ( + dfs(node.right, value) + + TreapNode.getSize(node.left) + + node.count + ); + } + + return 0; + }; + const res = dfs(this.root, value) - 1; + return isExist ? res : -1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns the index of the last occurrence of a value in the set, or -1 if it is not present. + */ + lastIndexOf(value: T): number { + const compare = this.compareFn; + let isExist = false; + + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + isExist = true; + return TreapNode.getSize(node.left) + node.count - 1; + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return ( + dfs(node.right, value) + + TreapNode.getSize(node.left) + + node.count + ); + } + + return 0; + }; + + const res = dfs(this.root, value) - 1; + return isExist ? res : -1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns the item located at the specified index. + * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): T | undefined { + if (index < 0) index += this.size; + if (index < 0 || index >= this.size) return undefined; + + const dfs = ( + node: TreapNode | null, + rank: number, + ): T | undefined => { + if (node == null) return undefined; + + if (TreapNode.getSize(node.left) >= rank) { + return dfs(node.left, rank); + } else if (TreapNode.getSize(node.left) + node.count >= rank) { + return node.value; + } else { + return dfs( + node.right, + rank - TreapNode.getSize(node.left) - node.count, + ); + } + }; + + const res = dfs(this.root, index + 2); + return ([this.leftBound, this.rightBound] as any[]).includes(res) + ? undefined + : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element less than `val`, return `undefined` if no such element found. + */ + lower(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) >= 0) return dfs(node.left, value); + + const tmp = dfs(node.right, value); + if (tmp == null || compare(node.value, tmp) > 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.leftBound ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element greater than `val`, return `undefined` if no such element found. + */ + higher(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) <= 0) return dfs(node.right, value); + + const tmp = dfs(node.left, value); + + if (tmp == null || compare(node.value, tmp) < 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.rightBound ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element less than or equal to `val`, return `undefined` if no such element found. + */ + floor(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) === 0) return node.value; + if (compare(node.value, value) >= 0) return dfs(node.left, value); + + const tmp = dfs(node.right, value); + if (tmp == null || compare(node.value, tmp) > 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.leftBound ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element greater than or equal to `val`, return `undefined` if no such element found. + */ + ceil(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) === 0) return node.value; + if (compare(node.value, value) <= 0) return dfs(node.right, value); + + const tmp = dfs(node.left, value); + + if (tmp == null || compare(node.value, tmp) < 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.rightBound ? undefined : res; + } + + /** + * @complexity `O(logn)` + * @description + * Returns the last element from set. + * If the set is empty, undefined is returned. + */ + first(): T | undefined { + const iter = this.inOrder(); + iter.next(); + const res = iter.next().value; + return res === this.rightBound ? undefined : res; + } + + /** + * @complexity `O(logn)` + * @description + * Returns the last element from set. + * If the set is empty, undefined is returned . + */ + last(): T | undefined { + const iter = this.reverseInOrder(); + iter.next(); + const res = iter.next().value; + return res === this.leftBound ? undefined : res; + } + + /** + * @complexity `O(logn)` + * @description + * Removes the first element from an set and returns it. + * If the set is empty, undefined is returned and the set is not modified. + */ + shift(): T | undefined { + const first = this.first(); + if (first === undefined) return undefined; + this.delete(first); + return first; + } + + /** + * @complexity `O(logn)` + * @description + * Removes the last element from an set and returns it. + * If the set is empty, undefined is returned and the set is not modified. + */ + pop(index?: number): T | undefined { + if (index == null) { + const last = this.last(); + if (last === undefined) return undefined; + this.delete(last); + return last; + } + + const toDelete = this.at(index); + if (toDelete == null) return; + this.delete(toDelete); + return toDelete; + } + + /** + * + * @complexity `O(logn)` + * @description + * Returns number of occurrences of value in the sorted set. + */ + count(value: T): number { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + if (compare(node.value, value) === 0) return node.count; + if (compare(node.value, value) < 0) return dfs(node.right, value); + return dfs(node.left, value); + }; + + return dfs(this.root, value); + } + + *[Symbol.iterator](): Generator { + yield* this.values(); + } + + /** + * @description + * Returns an iterable of keys in the set. + */ + *keys(): Generator { + yield* this.values(); + } + + /** + * @description + * Returns an iterable of values in the set. + */ + *values(): Generator { + const iter = this.inOrder(); + iter.next(); + const steps = this.size; + for (let _ = 0; _ < steps; _++) { + yield iter.next().value; + } + } + + /** + * @description + * Returns a generator for reversed order traversing the set. + */ + *rvalues(): Generator { + const iter = this.reverseInOrder(); + iter.next(); + const steps = this.size; + for (let _ = 0; _ < steps; _++) { + yield iter.next().value; + } + } + + /** + * @description + * Returns an iterable of key, value pairs for every entry in the set. + */ + *entries(): IterableIterator<[number, T]> { + const iter = this.inOrder(); + iter.next(); + const steps = this.size; + for (let i = 0; i < steps; i++) { + yield [i, iter.next().value]; + } + } + + private *inOrder( + root: TreapNode | null = this.root, + ): Generator { + if (root == null) return; + yield* this.inOrder(root.left); + const count = root.count; + for (let _ = 0; _ < count; _++) { + yield root.value; + } + yield* this.inOrder(root.right); + } + + private *reverseInOrder( + root: TreapNode | null = this.root, + ): Generator { + if (root == null) return; + yield* this.reverseInOrder(root.right); + const count = root.count; + for (let _ = 0; _ < count; _++) { + yield root.value; + } + yield* this.reverseInOrder(root.left); + } +} +```` + ### **...** ``` diff --git a/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README_EN.md b/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README_EN.md index 277cd783dbcbb..6789619b12665 100644 --- a/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README_EN.md +++ b/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/README_EN.md @@ -155,6 +155,716 @@ func max(a, b int) int { } ``` +### **TypeScript** + +````ts +function longestSubarray(nums: number[], limit: number): number { + const ts = new TreapMultiSet(); + let ans = 0; + let j = 0; + for (let i = 0; i < nums.length; ++i) { + ts.add(nums[i]); + while (ts.last() - ts.first() > limit) { + ts.delete(nums[j++]); + } + ans = Math.max(ans, i - j + 1); + } + return ans; +} + +type CompareFunction = ( + a: T, + b: T, +) => R extends 'number' ? number : boolean; + +interface ITreapMultiSet extends Iterable { + add: (...value: T[]) => this; + has: (value: T) => boolean; + delete: (value: T) => void; + + bisectLeft: (value: T) => number; + bisectRight: (value: T) => number; + + indexOf: (value: T) => number; + lastIndexOf: (value: T) => number; + + at: (index: number) => T | undefined; + first: () => T | undefined; + last: () => T | undefined; + + lower: (value: T) => T | undefined; + higher: (value: T) => T | undefined; + floor: (value: T) => T | undefined; + ceil: (value: T) => T | undefined; + + shift: () => T | undefined; + pop: (index?: number) => T | undefined; + + count: (value: T) => number; + + keys: () => IterableIterator; + values: () => IterableIterator; + rvalues: () => IterableIterator; + entries: () => IterableIterator<[number, T]>; + + readonly size: number; +} + +class TreapNode { + value: T; + count: number; + size: number; + priority: number; + left: TreapNode | null; + right: TreapNode | null; + + constructor(value: T) { + this.value = value; + this.count = 1; + this.size = 1; + this.priority = Math.random(); + this.left = null; + this.right = null; + } + + static getSize(node: TreapNode | null): number { + return node?.size ?? 0; + } + + static getFac(node: TreapNode | null): number { + return node?.priority ?? 0; + } + + pushUp(): void { + let tmp = this.count; + tmp += TreapNode.getSize(this.left); + tmp += TreapNode.getSize(this.right); + this.size = tmp; + } + + rotateRight(): TreapNode { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let node: TreapNode = this; + const left = node.left; + node.left = left?.right ?? null; + left && (left.right = node); + left && (node = left); + node.right?.pushUp(); + node.pushUp(); + return node; + } + + rotateLeft(): TreapNode { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let node: TreapNode = this; + const right = node.right; + node.right = right?.left ?? null; + right && (right.left = node); + right && (node = right); + node.left?.pushUp(); + node.pushUp(); + return node; + } +} + +class TreapMultiSet implements ITreapMultiSet { + private readonly root: TreapNode; + private readonly compareFn: CompareFunction; + private readonly leftBound: T; + private readonly rightBound: T; + + /** + * + * @param compareFn A compare function which returns boolean or number + * @param leftBound defalut value is `-Infinity` + * @param rightBound defalut value is `Infinity` + * @description + * create a `MultiSet`, compare elements using `compareFn`, which is increasing order by default. + * @example + * ```ts + * interface Person { + name: string + age: number + } + + const leftBound = { + name: 'Alice', + age: -Infinity, + } + + const rightBound = { + name: 'Bob', + age: Infinity, + } + + const sortedList = new TreapMultiSet( + (a: Person, b: Person) => a.age - b.age, + leftBound, + rightBound + ) + * ``` + */ + constructor(compareFn?: CompareFunction); + constructor( + compareFn: CompareFunction, + leftBound: T, + rightBound: T, + ); + constructor( + compareFn: CompareFunction = (a: any, b: any) => a - b, + leftBound: any = -Infinity, + rightBound: any = Infinity, + ) { + this.root = new TreapNode(rightBound); + this.root.priority = Infinity; + this.root.left = new TreapNode(leftBound); + this.root.left.priority = -Infinity; + this.root.pushUp(); + + this.leftBound = leftBound; + this.rightBound = rightBound; + this.compareFn = compareFn; + } + + get size(): number { + return this.root.size - 2; + } + + get height(): number { + const getHeight = (node: TreapNode | null): number => { + if (node == null) return 0; + return 1 + Math.max(getHeight(node.left), getHeight(node.right)); + }; + + return getHeight(this.root); + } + + /** + * + * @complexity `O(logn)` + * @description Returns true if value is a member. + */ + has(value: T): boolean { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): boolean => { + if (node == null) return false; + if (compare(node.value, value) === 0) return true; + if (compare(node.value, value) < 0) return dfs(node.right, value); + return dfs(node.left, value); + }; + + return dfs(this.root, value); + } + + /** + * + * @complexity `O(logn)` + * @description Add value to sorted set. + */ + add(...values: T[]): this { + const compare = this.compareFn; + const dfs = ( + node: TreapNode | null, + value: T, + parent: TreapNode, + direction: 'left' | 'right', + ): void => { + if (node == null) return; + if (compare(node.value, value) === 0) { + node.count++; + node.pushUp(); + } else if (compare(node.value, value) > 0) { + if (node.left) { + dfs(node.left, value, node, 'left'); + } else { + node.left = new TreapNode(value); + node.pushUp(); + } + + if (TreapNode.getFac(node.left) > node.priority) { + parent[direction] = node.rotateRight(); + } + } else if (compare(node.value, value) < 0) { + if (node.right) { + dfs(node.right, value, node, 'right'); + } else { + node.right = new TreapNode(value); + node.pushUp(); + } + + if (TreapNode.getFac(node.right) > node.priority) { + parent[direction] = node.rotateLeft(); + } + } + parent.pushUp(); + }; + + values.forEach(value => dfs(this.root.left, value, this.root, 'left')); + return this; + } + + /** + * + * @complexity `O(logn)` + * @description Remove value from sorted set if it is a member. + * If value is not a member, do nothing. + */ + delete(value: T): void { + const compare = this.compareFn; + const dfs = ( + node: TreapNode | null, + value: T, + parent: TreapNode, + direction: 'left' | 'right', + ): void => { + if (node == null) return; + + if (compare(node.value, value) === 0) { + if (node.count > 1) { + node.count--; + node?.pushUp(); + } else if (node.left == null && node.right == null) { + parent[direction] = null; + } else { + // 旋到根节点 + if ( + node.right == null || + TreapNode.getFac(node.left) > + TreapNode.getFac(node.right) + ) { + parent[direction] = node.rotateRight(); + dfs( + parent[direction]?.right ?? null, + value, + parent[direction]!, + 'right', + ); + } else { + parent[direction] = node.rotateLeft(); + dfs( + parent[direction]?.left ?? null, + value, + parent[direction]!, + 'left', + ); + } + } + } else if (compare(node.value, value) > 0) { + dfs(node.left, value, node, 'left'); + } else if (compare(node.value, value) < 0) { + dfs(node.right, value, node, 'right'); + } + + parent?.pushUp(); + }; + + dfs(this.root.left, value, this.root, 'left'); + } + + /** + * + * @complexity `O(logn)` + * @description Returns an index to insert value in the sorted set. + * If the value is already present, the insertion point will be before (to the left of) any existing values. + */ + bisectLeft(value: T): number { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + return TreapNode.getSize(node.left); + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return ( + dfs(node.right, value) + + TreapNode.getSize(node.left) + + node.count + ); + } + + return 0; + }; + + return dfs(this.root, value) - 1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns an index to insert value in the sorted set. + * If the value is already present, the insertion point will be before (to the right of) any existing values. + */ + bisectRight(value: T): number { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + return TreapNode.getSize(node.left) + node.count; + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return ( + dfs(node.right, value) + + TreapNode.getSize(node.left) + + node.count + ); + } + + return 0; + }; + return dfs(this.root, value) - 1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns the index of the first occurrence of a value in the set, or -1 if it is not present. + */ + indexOf(value: T): number { + const compare = this.compareFn; + let isExist = false; + + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + isExist = true; + return TreapNode.getSize(node.left); + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return ( + dfs(node.right, value) + + TreapNode.getSize(node.left) + + node.count + ); + } + + return 0; + }; + const res = dfs(this.root, value) - 1; + return isExist ? res : -1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns the index of the last occurrence of a value in the set, or -1 if it is not present. + */ + lastIndexOf(value: T): number { + const compare = this.compareFn; + let isExist = false; + + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + isExist = true; + return TreapNode.getSize(node.left) + node.count - 1; + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return ( + dfs(node.right, value) + + TreapNode.getSize(node.left) + + node.count + ); + } + + return 0; + }; + + const res = dfs(this.root, value) - 1; + return isExist ? res : -1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns the item located at the specified index. + * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): T | undefined { + if (index < 0) index += this.size; + if (index < 0 || index >= this.size) return undefined; + + const dfs = ( + node: TreapNode | null, + rank: number, + ): T | undefined => { + if (node == null) return undefined; + + if (TreapNode.getSize(node.left) >= rank) { + return dfs(node.left, rank); + } else if (TreapNode.getSize(node.left) + node.count >= rank) { + return node.value; + } else { + return dfs( + node.right, + rank - TreapNode.getSize(node.left) - node.count, + ); + } + }; + + const res = dfs(this.root, index + 2); + return ([this.leftBound, this.rightBound] as any[]).includes(res) + ? undefined + : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element less than `val`, return `undefined` if no such element found. + */ + lower(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) >= 0) return dfs(node.left, value); + + const tmp = dfs(node.right, value); + if (tmp == null || compare(node.value, tmp) > 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.leftBound ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element greater than `val`, return `undefined` if no such element found. + */ + higher(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) <= 0) return dfs(node.right, value); + + const tmp = dfs(node.left, value); + + if (tmp == null || compare(node.value, tmp) < 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.rightBound ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element less than or equal to `val`, return `undefined` if no such element found. + */ + floor(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) === 0) return node.value; + if (compare(node.value, value) >= 0) return dfs(node.left, value); + + const tmp = dfs(node.right, value); + if (tmp == null || compare(node.value, tmp) > 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.leftBound ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element greater than or equal to `val`, return `undefined` if no such element found. + */ + ceil(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) === 0) return node.value; + if (compare(node.value, value) <= 0) return dfs(node.right, value); + + const tmp = dfs(node.left, value); + + if (tmp == null || compare(node.value, tmp) < 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.rightBound ? undefined : res; + } + + /** + * @complexity `O(logn)` + * @description + * Returns the last element from set. + * If the set is empty, undefined is returned. + */ + first(): T | undefined { + const iter = this.inOrder(); + iter.next(); + const res = iter.next().value; + return res === this.rightBound ? undefined : res; + } + + /** + * @complexity `O(logn)` + * @description + * Returns the last element from set. + * If the set is empty, undefined is returned . + */ + last(): T | undefined { + const iter = this.reverseInOrder(); + iter.next(); + const res = iter.next().value; + return res === this.leftBound ? undefined : res; + } + + /** + * @complexity `O(logn)` + * @description + * Removes the first element from an set and returns it. + * If the set is empty, undefined is returned and the set is not modified. + */ + shift(): T | undefined { + const first = this.first(); + if (first === undefined) return undefined; + this.delete(first); + return first; + } + + /** + * @complexity `O(logn)` + * @description + * Removes the last element from an set and returns it. + * If the set is empty, undefined is returned and the set is not modified. + */ + pop(index?: number): T | undefined { + if (index == null) { + const last = this.last(); + if (last === undefined) return undefined; + this.delete(last); + return last; + } + + const toDelete = this.at(index); + if (toDelete == null) return; + this.delete(toDelete); + return toDelete; + } + + /** + * + * @complexity `O(logn)` + * @description + * Returns number of occurrences of value in the sorted set. + */ + count(value: T): number { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + if (compare(node.value, value) === 0) return node.count; + if (compare(node.value, value) < 0) return dfs(node.right, value); + return dfs(node.left, value); + }; + + return dfs(this.root, value); + } + + *[Symbol.iterator](): Generator { + yield* this.values(); + } + + /** + * @description + * Returns an iterable of keys in the set. + */ + *keys(): Generator { + yield* this.values(); + } + + /** + * @description + * Returns an iterable of values in the set. + */ + *values(): Generator { + const iter = this.inOrder(); + iter.next(); + const steps = this.size; + for (let _ = 0; _ < steps; _++) { + yield iter.next().value; + } + } + + /** + * @description + * Returns a generator for reversed order traversing the set. + */ + *rvalues(): Generator { + const iter = this.reverseInOrder(); + iter.next(); + const steps = this.size; + for (let _ = 0; _ < steps; _++) { + yield iter.next().value; + } + } + + /** + * @description + * Returns an iterable of key, value pairs for every entry in the set. + */ + *entries(): IterableIterator<[number, T]> { + const iter = this.inOrder(); + iter.next(); + const steps = this.size; + for (let i = 0; i < steps; i++) { + yield [i, iter.next().value]; + } + } + + private *inOrder( + root: TreapNode | null = this.root, + ): Generator { + if (root == null) return; + yield* this.inOrder(root.left); + const count = root.count; + for (let _ = 0; _ < count; _++) { + yield root.value; + } + yield* this.inOrder(root.right); + } + + private *reverseInOrder( + root: TreapNode | null = this.root, + ): Generator { + if (root == null) return; + yield* this.reverseInOrder(root.right); + const count = root.count; + for (let _ = 0; _ < count; _++) { + yield root.value; + } + yield* this.reverseInOrder(root.left); + } +} +```` + ### **...** ``` diff --git a/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/Solution.ts b/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/Solution.ts new file mode 100644 index 0000000000000..4da581823c184 --- /dev/null +++ b/solution/1400-1499/1438.Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit/Solution.ts @@ -0,0 +1,705 @@ +function longestSubarray(nums: number[], limit: number): number { + const ts = new TreapMultiSet(); + let ans = 0; + let j = 0; + for (let i = 0; i < nums.length; ++i) { + ts.add(nums[i]); + while (ts.last() - ts.first() > limit) { + ts.delete(nums[j++]); + } + ans = Math.max(ans, i - j + 1); + } + return ans; +} + +type CompareFunction = ( + a: T, + b: T, +) => R extends 'number' ? number : boolean; + +interface ITreapMultiSet extends Iterable { + add: (...value: T[]) => this; + has: (value: T) => boolean; + delete: (value: T) => void; + + bisectLeft: (value: T) => number; + bisectRight: (value: T) => number; + + indexOf: (value: T) => number; + lastIndexOf: (value: T) => number; + + at: (index: number) => T | undefined; + first: () => T | undefined; + last: () => T | undefined; + + lower: (value: T) => T | undefined; + higher: (value: T) => T | undefined; + floor: (value: T) => T | undefined; + ceil: (value: T) => T | undefined; + + shift: () => T | undefined; + pop: (index?: number) => T | undefined; + + count: (value: T) => number; + + keys: () => IterableIterator; + values: () => IterableIterator; + rvalues: () => IterableIterator; + entries: () => IterableIterator<[number, T]>; + + readonly size: number; +} + +class TreapNode { + value: T; + count: number; + size: number; + priority: number; + left: TreapNode | null; + right: TreapNode | null; + + constructor(value: T) { + this.value = value; + this.count = 1; + this.size = 1; + this.priority = Math.random(); + this.left = null; + this.right = null; + } + + static getSize(node: TreapNode | null): number { + return node?.size ?? 0; + } + + static getFac(node: TreapNode | null): number { + return node?.priority ?? 0; + } + + pushUp(): void { + let tmp = this.count; + tmp += TreapNode.getSize(this.left); + tmp += TreapNode.getSize(this.right); + this.size = tmp; + } + + rotateRight(): TreapNode { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let node: TreapNode = this; + const left = node.left; + node.left = left?.right ?? null; + left && (left.right = node); + left && (node = left); + node.right?.pushUp(); + node.pushUp(); + return node; + } + + rotateLeft(): TreapNode { + // eslint-disable-next-line @typescript-eslint/no-this-alias + let node: TreapNode = this; + const right = node.right; + node.right = right?.left ?? null; + right && (right.left = node); + right && (node = right); + node.left?.pushUp(); + node.pushUp(); + return node; + } +} + +class TreapMultiSet implements ITreapMultiSet { + private readonly root: TreapNode; + private readonly compareFn: CompareFunction; + private readonly leftBound: T; + private readonly rightBound: T; + + /** + * + * @param compareFn A compare function which returns boolean or number + * @param leftBound defalut value is `-Infinity` + * @param rightBound defalut value is `Infinity` + * @description + * create a `MultiSet`, compare elements using `compareFn`, which is increasing order by default. + * @example + * ```ts + * interface Person { + name: string + age: number + } + + const leftBound = { + name: 'Alice', + age: -Infinity, + } + + const rightBound = { + name: 'Bob', + age: Infinity, + } + + const sortedList = new TreapMultiSet( + (a: Person, b: Person) => a.age - b.age, + leftBound, + rightBound + ) + * ``` + */ + constructor(compareFn?: CompareFunction); + constructor( + compareFn: CompareFunction, + leftBound: T, + rightBound: T, + ); + constructor( + compareFn: CompareFunction = (a: any, b: any) => a - b, + leftBound: any = -Infinity, + rightBound: any = Infinity, + ) { + this.root = new TreapNode(rightBound); + this.root.priority = Infinity; + this.root.left = new TreapNode(leftBound); + this.root.left.priority = -Infinity; + this.root.pushUp(); + + this.leftBound = leftBound; + this.rightBound = rightBound; + this.compareFn = compareFn; + } + + get size(): number { + return this.root.size - 2; + } + + get height(): number { + const getHeight = (node: TreapNode | null): number => { + if (node == null) return 0; + return 1 + Math.max(getHeight(node.left), getHeight(node.right)); + }; + + return getHeight(this.root); + } + + /** + * + * @complexity `O(logn)` + * @description Returns true if value is a member. + */ + has(value: T): boolean { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): boolean => { + if (node == null) return false; + if (compare(node.value, value) === 0) return true; + if (compare(node.value, value) < 0) return dfs(node.right, value); + return dfs(node.left, value); + }; + + return dfs(this.root, value); + } + + /** + * + * @complexity `O(logn)` + * @description Add value to sorted set. + */ + add(...values: T[]): this { + const compare = this.compareFn; + const dfs = ( + node: TreapNode | null, + value: T, + parent: TreapNode, + direction: 'left' | 'right', + ): void => { + if (node == null) return; + if (compare(node.value, value) === 0) { + node.count++; + node.pushUp(); + } else if (compare(node.value, value) > 0) { + if (node.left) { + dfs(node.left, value, node, 'left'); + } else { + node.left = new TreapNode(value); + node.pushUp(); + } + + if (TreapNode.getFac(node.left) > node.priority) { + parent[direction] = node.rotateRight(); + } + } else if (compare(node.value, value) < 0) { + if (node.right) { + dfs(node.right, value, node, 'right'); + } else { + node.right = new TreapNode(value); + node.pushUp(); + } + + if (TreapNode.getFac(node.right) > node.priority) { + parent[direction] = node.rotateLeft(); + } + } + parent.pushUp(); + }; + + values.forEach(value => dfs(this.root.left, value, this.root, 'left')); + return this; + } + + /** + * + * @complexity `O(logn)` + * @description Remove value from sorted set if it is a member. + * If value is not a member, do nothing. + */ + delete(value: T): void { + const compare = this.compareFn; + const dfs = ( + node: TreapNode | null, + value: T, + parent: TreapNode, + direction: 'left' | 'right', + ): void => { + if (node == null) return; + + if (compare(node.value, value) === 0) { + if (node.count > 1) { + node.count--; + node?.pushUp(); + } else if (node.left == null && node.right == null) { + parent[direction] = null; + } else { + // 旋到根节点 + if ( + node.right == null || + TreapNode.getFac(node.left) > + TreapNode.getFac(node.right) + ) { + parent[direction] = node.rotateRight(); + dfs( + parent[direction]?.right ?? null, + value, + parent[direction]!, + 'right', + ); + } else { + parent[direction] = node.rotateLeft(); + dfs( + parent[direction]?.left ?? null, + value, + parent[direction]!, + 'left', + ); + } + } + } else if (compare(node.value, value) > 0) { + dfs(node.left, value, node, 'left'); + } else if (compare(node.value, value) < 0) { + dfs(node.right, value, node, 'right'); + } + + parent?.pushUp(); + }; + + dfs(this.root.left, value, this.root, 'left'); + } + + /** + * + * @complexity `O(logn)` + * @description Returns an index to insert value in the sorted set. + * If the value is already present, the insertion point will be before (to the left of) any existing values. + */ + bisectLeft(value: T): number { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + return TreapNode.getSize(node.left); + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return ( + dfs(node.right, value) + + TreapNode.getSize(node.left) + + node.count + ); + } + + return 0; + }; + + return dfs(this.root, value) - 1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns an index to insert value in the sorted set. + * If the value is already present, the insertion point will be before (to the right of) any existing values. + */ + bisectRight(value: T): number { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + return TreapNode.getSize(node.left) + node.count; + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return ( + dfs(node.right, value) + + TreapNode.getSize(node.left) + + node.count + ); + } + + return 0; + }; + return dfs(this.root, value) - 1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns the index of the first occurrence of a value in the set, or -1 if it is not present. + */ + indexOf(value: T): number { + const compare = this.compareFn; + let isExist = false; + + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + isExist = true; + return TreapNode.getSize(node.left); + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return ( + dfs(node.right, value) + + TreapNode.getSize(node.left) + + node.count + ); + } + + return 0; + }; + const res = dfs(this.root, value) - 1; + return isExist ? res : -1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns the index of the last occurrence of a value in the set, or -1 if it is not present. + */ + lastIndexOf(value: T): number { + const compare = this.compareFn; + let isExist = false; + + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + + if (compare(node.value, value) === 0) { + isExist = true; + return TreapNode.getSize(node.left) + node.count - 1; + } else if (compare(node.value, value) > 0) { + return dfs(node.left, value); + } else if (compare(node.value, value) < 0) { + return ( + dfs(node.right, value) + + TreapNode.getSize(node.left) + + node.count + ); + } + + return 0; + }; + + const res = dfs(this.root, value) - 1; + return isExist ? res : -1; + } + + /** + * + * @complexity `O(logn)` + * @description Returns the item located at the specified index. + * @param index The zero-based index of the desired code unit. A negative index will count back from the last item. + */ + at(index: number): T | undefined { + if (index < 0) index += this.size; + if (index < 0 || index >= this.size) return undefined; + + const dfs = ( + node: TreapNode | null, + rank: number, + ): T | undefined => { + if (node == null) return undefined; + + if (TreapNode.getSize(node.left) >= rank) { + return dfs(node.left, rank); + } else if (TreapNode.getSize(node.left) + node.count >= rank) { + return node.value; + } else { + return dfs( + node.right, + rank - TreapNode.getSize(node.left) - node.count, + ); + } + }; + + const res = dfs(this.root, index + 2); + return ([this.leftBound, this.rightBound] as any[]).includes(res) + ? undefined + : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element less than `val`, return `undefined` if no such element found. + */ + lower(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) >= 0) return dfs(node.left, value); + + const tmp = dfs(node.right, value); + if (tmp == null || compare(node.value, tmp) > 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.leftBound ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element greater than `val`, return `undefined` if no such element found. + */ + higher(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) <= 0) return dfs(node.right, value); + + const tmp = dfs(node.left, value); + + if (tmp == null || compare(node.value, tmp) < 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.rightBound ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element less than or equal to `val`, return `undefined` if no such element found. + */ + floor(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) === 0) return node.value; + if (compare(node.value, value) >= 0) return dfs(node.left, value); + + const tmp = dfs(node.right, value); + if (tmp == null || compare(node.value, tmp) > 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.leftBound ? undefined : res; + } + + /** + * + * @complexity `O(logn)` + * @description Find and return the element greater than or equal to `val`, return `undefined` if no such element found. + */ + ceil(value: T): T | undefined { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): T | undefined => { + if (node == null) return undefined; + if (compare(node.value, value) === 0) return node.value; + if (compare(node.value, value) <= 0) return dfs(node.right, value); + + const tmp = dfs(node.left, value); + + if (tmp == null || compare(node.value, tmp) < 0) { + return node.value; + } else { + return tmp; + } + }; + + const res = dfs(this.root, value) as any; + return res === this.rightBound ? undefined : res; + } + + /** + * @complexity `O(logn)` + * @description + * Returns the last element from set. + * If the set is empty, undefined is returned. + */ + first(): T | undefined { + const iter = this.inOrder(); + iter.next(); + const res = iter.next().value; + return res === this.rightBound ? undefined : res; + } + + /** + * @complexity `O(logn)` + * @description + * Returns the last element from set. + * If the set is empty, undefined is returned . + */ + last(): T | undefined { + const iter = this.reverseInOrder(); + iter.next(); + const res = iter.next().value; + return res === this.leftBound ? undefined : res; + } + + /** + * @complexity `O(logn)` + * @description + * Removes the first element from an set and returns it. + * If the set is empty, undefined is returned and the set is not modified. + */ + shift(): T | undefined { + const first = this.first(); + if (first === undefined) return undefined; + this.delete(first); + return first; + } + + /** + * @complexity `O(logn)` + * @description + * Removes the last element from an set and returns it. + * If the set is empty, undefined is returned and the set is not modified. + */ + pop(index?: number): T | undefined { + if (index == null) { + const last = this.last(); + if (last === undefined) return undefined; + this.delete(last); + return last; + } + + const toDelete = this.at(index); + if (toDelete == null) return; + this.delete(toDelete); + return toDelete; + } + + /** + * + * @complexity `O(logn)` + * @description + * Returns number of occurrences of value in the sorted set. + */ + count(value: T): number { + const compare = this.compareFn; + const dfs = (node: TreapNode | null, value: T): number => { + if (node == null) return 0; + if (compare(node.value, value) === 0) return node.count; + if (compare(node.value, value) < 0) return dfs(node.right, value); + return dfs(node.left, value); + }; + + return dfs(this.root, value); + } + + *[Symbol.iterator](): Generator { + yield* this.values(); + } + + /** + * @description + * Returns an iterable of keys in the set. + */ + *keys(): Generator { + yield* this.values(); + } + + /** + * @description + * Returns an iterable of values in the set. + */ + *values(): Generator { + const iter = this.inOrder(); + iter.next(); + const steps = this.size; + for (let _ = 0; _ < steps; _++) { + yield iter.next().value; + } + } + + /** + * @description + * Returns a generator for reversed order traversing the set. + */ + *rvalues(): Generator { + const iter = this.reverseInOrder(); + iter.next(); + const steps = this.size; + for (let _ = 0; _ < steps; _++) { + yield iter.next().value; + } + } + + /** + * @description + * Returns an iterable of key, value pairs for every entry in the set. + */ + *entries(): IterableIterator<[number, T]> { + const iter = this.inOrder(); + iter.next(); + const steps = this.size; + for (let i = 0; i < steps; i++) { + yield [i, iter.next().value]; + } + } + + private *inOrder( + root: TreapNode | null = this.root, + ): Generator { + if (root == null) return; + yield* this.inOrder(root.left); + const count = root.count; + for (let _ = 0; _ < count; _++) { + yield root.value; + } + yield* this.inOrder(root.right); + } + + private *reverseInOrder( + root: TreapNode | null = this.root, + ): Generator { + if (root == null) return; + yield* this.reverseInOrder(root.right); + const count = root.count; + for (let _ = 0; _ < count; _++) { + yield root.value; + } + yield* this.reverseInOrder(root.left); + } +} diff --git a/solution/1400-1499/1473.Paint House III/README.md b/solution/1400-1499/1473.Paint House III/README.md index 3edc3641e229e..35a1e5a4f0d84 100644 --- a/solution/1400-1499/1473.Paint House III/README.md +++ b/solution/1400-1499/1473.Paint House III/README.md @@ -164,7 +164,8 @@ class Solution { if (j == j0) { f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j][k] + cost[i][j - 1]); } else { - f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j0][k - 1] + cost[i][j - 1]); + f[i][j][k] + = Math.min(f[i][j][k], f[i - 1][j0][k - 1] + cost[i][j - 1]); } } } diff --git a/solution/1400-1499/1473.Paint House III/README_EN.md b/solution/1400-1499/1473.Paint House III/README_EN.md index 503c70ff63cee..4187b9f0b2a11 100644 --- a/solution/1400-1499/1473.Paint House III/README_EN.md +++ b/solution/1400-1499/1473.Paint House III/README_EN.md @@ -129,7 +129,8 @@ class Solution { if (j == j0) { f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j][k] + cost[i][j - 1]); } else { - f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j0][k - 1] + cost[i][j - 1]); + f[i][j][k] + = Math.min(f[i][j][k], f[i - 1][j0][k - 1] + cost[i][j - 1]); } } } diff --git a/solution/1400-1499/1473.Paint House III/Solution.java b/solution/1400-1499/1473.Paint House III/Solution.java index a28cab77ec96b..e6a085b29a437 100644 --- a/solution/1400-1499/1473.Paint House III/Solution.java +++ b/solution/1400-1499/1473.Paint House III/Solution.java @@ -22,7 +22,8 @@ public int minCost(int[] houses, int[][] cost, int m, int n, int target) { if (j == j0) { f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j][k] + cost[i][j - 1]); } else { - f[i][j][k] = Math.min(f[i][j][k], f[i - 1][j0][k - 1] + cost[i][j - 1]); + f[i][j][k] + = Math.min(f[i][j][k], f[i - 1][j0][k - 1] + cost[i][j - 1]); } } } diff --git a/solution/1500-1599/1588.Sum of All Odd Length Subarrays/Solution.c b/solution/1500-1599/1588.Sum of All Odd Length Subarrays/Solution.c index 6a76b963f616c..76cd62eafe0d3 100644 --- a/solution/1500-1599/1588.Sum of All Odd Length Subarrays/Solution.c +++ b/solution/1500-1599/1588.Sum of All Odd Length Subarrays/Solution.c @@ -1,4 +1,4 @@ -int sumOddLengthSubarrays(int* arr, int arrSize){ +int sumOddLengthSubarrays(int* arr, int arrSize) { int ans = 0; for (int i = 0; i < arrSize; ++i) { int s = 0; diff --git a/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README.md b/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README.md index 4adb1cd59c456..b83ca3423ac30 100644 --- a/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README.md +++ b/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README.md @@ -97,7 +97,7 @@ class Solution { public int maxSumRangeQuery(int[] nums, int[][] requests) { int n = nums.length; int[] d = new int[n]; - for (var req: requests) { + for (var req : requests) { int l = req[0], r = req[1]; d[l]++; if (r + 1 < n) { diff --git a/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README_EN.md b/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README_EN.md index 27bd3aa32312c..46eaaedbd4ec2 100644 --- a/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README_EN.md +++ b/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/README_EN.md @@ -82,7 +82,7 @@ class Solution { public int maxSumRangeQuery(int[] nums, int[][] requests) { int n = nums.length; int[] d = new int[n]; - for (var req: requests) { + for (var req : requests) { int l = req[0], r = req[1]; d[l]++; if (r + 1 < n) { diff --git a/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/Solution.java b/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/Solution.java index 32cc79b8aca4a..2c2e78bd843dc 100644 --- a/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/Solution.java +++ b/solution/1500-1599/1589.Maximum Sum Obtained of Any Permutation/Solution.java @@ -2,7 +2,7 @@ class Solution { public int maxSumRangeQuery(int[] nums, int[][] requests) { int n = nums.length; int[] d = new int[n]; - for (var req: requests) { + for (var req : requests) { int l = req[0], r = req[1]; d[l]++; if (r + 1 < n) { diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README.md b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README.md index c4a3047885824..7253e684b6a12 100644 --- a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README.md +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README.md @@ -192,7 +192,7 @@ class Solution { char[] cs = s.toCharArray(); for (int j = 0; j < 10; ++j) { for (int k = 1; k < n; k += 2) { - cs[k] = (char) (((cs[k] - '0' + a) % 10) + '0'); + cs[k] = (char) (((cs[k] - '0' + a) % 10) + '0'); } if ((b & 1) == 1) { for (int p = 0; p < 10; ++p) { diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README_EN.md b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README_EN.md index 93b0d89d452b1..6a96bf4272fde 100644 --- a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README_EN.md +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/README_EN.md @@ -163,7 +163,7 @@ class Solution { char[] cs = s.toCharArray(); for (int j = 0; j < 10; ++j) { for (int k = 1; k < n; k += 2) { - cs[k] = (char) (((cs[k] - '0' + a) % 10) + '0'); + cs[k] = (char) (((cs[k] - '0' + a) % 10) + '0'); } if ((b & 1) == 1) { for (int p = 0; p < 10; ++p) { diff --git a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.java b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.java index 319c3edd89d3b..12f1c40ec78e2 100644 --- a/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.java +++ b/solution/1600-1699/1625.Lexicographically Smallest String After Applying Operations/Solution.java @@ -7,7 +7,7 @@ public String findLexSmallestString(String s, int a, int b) { char[] cs = s.toCharArray(); for (int j = 0; j < 10; ++j) { for (int k = 1; k < n; k += 2) { - cs[k] = (char) (((cs[k] - '0' + a) % 10) + '0'); + cs[k] = (char) (((cs[k] - '0' + a) % 10) + '0'); } if ((b & 1) == 1) { for (int p = 0; p < 10; ++p) { diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/README.md b/solution/1600-1699/1626.Best Team With No Conflicts/README.md index 00f642e44246c..cd019cea71ade 100644 --- a/solution/1600-1699/1626.Best Team With No Conflicts/README.md +++ b/solution/1600-1699/1626.Best Team With No Conflicts/README.md @@ -177,7 +177,6 @@ class BinaryIndexedTree { } } - class Solution { public int bestTeamScore(int[] scores, int[] ages) { int n = ages.length; diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/README_EN.md b/solution/1600-1699/1626.Best Team With No Conflicts/README_EN.md index e017998621e82..6931993a4f6fb 100644 --- a/solution/1600-1699/1626.Best Team With No Conflicts/README_EN.md +++ b/solution/1600-1699/1626.Best Team With No Conflicts/README_EN.md @@ -149,7 +149,6 @@ class BinaryIndexedTree { } } - class Solution { public int bestTeamScore(int[] scores, int[] ages) { int n = ages.length; diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/Solution.cpp b/solution/1600-1699/1626.Best Team With No Conflicts/Solution.cpp index 772de39cc74ae..a670d40eb118f 100644 --- a/solution/1600-1699/1626.Best Team With No Conflicts/Solution.cpp +++ b/solution/1600-1699/1626.Best Team With No Conflicts/Solution.cpp @@ -1,6 +1,8 @@ class BinaryIndexedTree { public: - BinaryIndexedTree(int _n) : n(_n), c(_n + 1) {} + BinaryIndexedTree(int _n) + : n(_n) + , c(_n + 1) {} void update(int x, int val) { while (x <= n) { diff --git a/solution/1600-1699/1626.Best Team With No Conflicts/Solution.java b/solution/1600-1699/1626.Best Team With No Conflicts/Solution.java index 8b8040798f8c5..25fea41b033ec 100644 --- a/solution/1600-1699/1626.Best Team With No Conflicts/Solution.java +++ b/solution/1600-1699/1626.Best Team With No Conflicts/Solution.java @@ -24,7 +24,6 @@ public int query(int x) { } } - class Solution { public int bestTeamScore(int[] scores, int[] ages) { int n = ages.length; diff --git a/solution/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/Solution.java b/solution/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/Solution.java index babadfe9c7ec4..903d22c9b31f0 100644 --- a/solution/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/Solution.java +++ b/solution/1600-1699/1644.Lowest Common Ancestor of a Binary Tree II/Solution.java @@ -12,7 +12,7 @@ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { dfs(root, p, q); - return ans; + return ans; } private boolean dfs(TreeNode root, TreeNode p, TreeNode q) { diff --git a/solution/1700-1799/1735.Count Ways to Make Array With Product/README.md b/solution/1700-1799/1735.Count Ways to Make Array With Product/README.md index d7f3f9c1194d8..e96659874822e 100644 --- a/solution/1700-1799/1735.Count Ways to Make Array With Product/README.md +++ b/solution/1700-1799/1735.Count Ways to Make Array With Product/README.md @@ -155,7 +155,6 @@ class Solution { return (F[n] * G[k] % MOD) * G[n - k] % MOD; } - public int[] waysToFillArray(int[][] queries) { int m = queries.length; int[] ans = new int[m]; diff --git a/solution/1700-1799/1735.Count Ways to Make Array With Product/README_EN.md b/solution/1700-1799/1735.Count Ways to Make Array With Product/README_EN.md index baa46fae49958..6595be2308a49 100644 --- a/solution/1700-1799/1735.Count Ways to Make Array With Product/README_EN.md +++ b/solution/1700-1799/1735.Count Ways to Make Array With Product/README_EN.md @@ -129,7 +129,6 @@ class Solution { return (F[n] * G[k] % MOD) * G[n - k] % MOD; } - public int[] waysToFillArray(int[][] queries) { int m = queries.length; int[] ans = new int[m]; diff --git a/solution/1700-1799/1735.Count Ways to Make Array With Product/Solution.java b/solution/1700-1799/1735.Count Ways to Make Array With Product/Solution.java index 693beac390574..9f57447eb44b7 100644 --- a/solution/1700-1799/1735.Count Ways to Make Array With Product/Solution.java +++ b/solution/1700-1799/1735.Count Ways to Make Array With Product/Solution.java @@ -45,7 +45,6 @@ public static long comb(int n, int k) { return (F[n] * G[k] % MOD) * G[n - k] % MOD; } - public int[] waysToFillArray(int[][] queries) { int m = queries.length; int[] ans = new int[m]; diff --git a/solution/1700-1799/1773.Count Items Matching a Rule/Solution.c b/solution/1700-1799/1773.Count Items Matching a Rule/Solution.c index c442adb66cd9a..a795862f97c65 100644 --- a/solution/1700-1799/1773.Count Items Matching a Rule/Solution.c +++ b/solution/1700-1799/1773.Count Items Matching a Rule/Solution.c @@ -1,5 +1,6 @@ int countMatches(char*** items, int itemsSize, int* itemsColSize, char* ruleKey, char* ruleValue) { - int k = strcmp(ruleKey, "type") == 0 ? 0 : strcmp(ruleKey, "color") == 0 ? 1 : 2; + int k = strcmp(ruleKey, "type") == 0 ? 0 : strcmp(ruleKey, "color") == 0 ? 1 + : 2; int res = 0; for (int i = 0; i < itemsSize; i++) { if (strcmp(items[i][k], ruleValue) == 0) { diff --git a/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README.md b/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README.md index df18a6a604efb..49089f72ea639 100644 --- a/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README.md +++ b/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README.md @@ -119,7 +119,7 @@ class Solution { Arrays.setAll(g, k -> new ArrayList<>()); for (int i = 1; i < n; ++i) { int p = edges[i][0], w = edges[i][1]; - g[p].add(new int[]{i, w}); + g[p].add(new int[] {i, w}); } return dfs(0)[1]; } @@ -134,7 +134,7 @@ class Solution { t = Math.max(t, s[0] - s[1] + w); } b += t; - return new long[]{a, b}; + return new long[] {a, b}; } } ``` diff --git a/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README_EN.md b/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README_EN.md index 8fb748617ddcd..99875eca10440 100644 --- a/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README_EN.md +++ b/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/README_EN.md @@ -94,7 +94,7 @@ class Solution { Arrays.setAll(g, k -> new ArrayList<>()); for (int i = 1; i < n; ++i) { int p = edges[i][0], w = edges[i][1]; - g[p].add(new int[]{i, w}); + g[p].add(new int[] {i, w}); } return dfs(0)[1]; } @@ -109,7 +109,7 @@ class Solution { t = Math.max(t, s[0] - s[1] + w); } b += t; - return new long[]{a, b}; + return new long[] {a, b}; } } ``` diff --git a/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/Solution.java b/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/Solution.java index d2edb16c47d2c..c9ba8557302f2 100644 --- a/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/Solution.java +++ b/solution/2300-2399/2378.Choose Edges to Maximize Score in a Tree/Solution.java @@ -7,7 +7,7 @@ public long maxScore(int[][] edges) { Arrays.setAll(g, k -> new ArrayList<>()); for (int i = 1; i < n; ++i) { int p = edges[i][0], w = edges[i][1]; - g[p].add(new int[]{i, w}); + g[p].add(new int[] {i, w}); } return dfs(0)[1]; } @@ -22,6 +22,6 @@ private long[] dfs(int i) { t = Math.max(t, s[0] - s[1] + w); } b += t; - return new long[]{a, b}; + return new long[] {a, b}; } } \ No newline at end of file diff --git a/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.c b/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.c index 43474935c48e8..8f11fcc24b25d 100644 --- a/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.c +++ b/solution/2300-2399/2379.Minimum Recolors to Get K Consecutive Black Blocks/Solution.c @@ -1,6 +1,6 @@ #define min(a, b) (((a) < (b)) ? (a) : (b)) -int minimumRecolors(char *blocks, int k) { +int minimumRecolors(char* blocks, int k) { int n = strlen(blocks); int count = 0; for (int i = 0; i < k; i++) { diff --git a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README.md b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README.md index f0a511c1ec8cd..1f579ef4da3ff 100644 --- a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README.md +++ b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README.md @@ -146,7 +146,8 @@ class Solution { ```java class Solution { - public int minNumberOfHours(int initialEnergy, int initialExperience, int[] energy, int[] experience) { + public int minNumberOfHours( + int initialEnergy, int initialExperience, int[] energy, int[] experience) { int s = 0; for (int x : energy) { s += x; diff --git a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README_EN.md b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README_EN.md index eab8227e42558..dac5de44e3213 100644 --- a/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README_EN.md +++ b/solution/2300-2399/2383.Minimum Hours of Training to Win a Competition/README_EN.md @@ -120,7 +120,8 @@ class Solution { ```java class Solution { - public int minNumberOfHours(int initialEnergy, int initialExperience, int[] energy, int[] experience) { + public int minNumberOfHours( + int initialEnergy, int initialExperience, int[] energy, int[] experience) { int s = 0; for (int x : energy) { s += x; diff --git a/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution.java b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution.java index a1fba7b6164a6..08b0a1cd8100c 100644 --- a/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution.java +++ b/solution/2300-2399/2389.Longest Subsequence With Limited Sum/Solution.java @@ -11,7 +11,7 @@ public int[] answerQueries(int[] nums, int[] queries) { } return ans; } - + private int search(int[] nums, int x) { int l = 0, r = nums.length; while (l < r) { diff --git a/solution/2300-2399/2395.Find Subarrays With Equal Sum/Solution.c b/solution/2300-2399/2395.Find Subarrays With Equal Sum/Solution.c index ca321d320584e..62be149a9da11 100644 --- a/solution/2300-2399/2395.Find Subarrays With Equal Sum/Solution.c +++ b/solution/2300-2399/2395.Find Subarrays With Equal Sum/Solution.c @@ -1,4 +1,4 @@ -bool findSubarrays(int *nums, int numsSize) { +bool findSubarrays(int* nums, int numsSize) { for (int i = 1; i < numsSize - 2; i++) { for (int j = i + 1; j < numsSize; j++) { if (nums[i - 1] + nums[i] == nums[j - 1] + nums[j]) { diff --git a/solution/2400-2499/2488.Count Subarrays With Median K/README.md b/solution/2400-2499/2488.Count Subarrays With Median K/README.md index 4eedc57be6338..eac4ef2b2f18b 100644 --- a/solution/2400-2499/2488.Count Subarrays With Median K/README.md +++ b/solution/2400-2499/2488.Count Subarrays With Median K/README.md @@ -104,7 +104,8 @@ class Solution { public int countSubarrays(int[] nums, int k) { int n = nums.length; int i = 0; - for (; nums[i] != k; ++i) {} + for (; nums[i] != k; ++i) { + } int[] cnt = new int[n << 1 | 1]; int ans = 1; int x = 0; diff --git a/solution/2400-2499/2488.Count Subarrays With Median K/README_EN.md b/solution/2400-2499/2488.Count Subarrays With Median K/README_EN.md index 778c2b2b0f7e2..325ced5c62b46 100644 --- a/solution/2400-2499/2488.Count Subarrays With Median K/README_EN.md +++ b/solution/2400-2499/2488.Count Subarrays With Median K/README_EN.md @@ -78,7 +78,8 @@ class Solution { public int countSubarrays(int[] nums, int k) { int n = nums.length; int i = 0; - for (; nums[i] != k; ++i) {} + for (; nums[i] != k; ++i) { + } int[] cnt = new int[n << 1 | 1]; int ans = 1; int x = 0; diff --git a/solution/2400-2499/2488.Count Subarrays With Median K/Solution.java b/solution/2400-2499/2488.Count Subarrays With Median K/Solution.java index 69abb16e4be43..080ca819b1a3b 100644 --- a/solution/2400-2499/2488.Count Subarrays With Median K/Solution.java +++ b/solution/2400-2499/2488.Count Subarrays With Median K/Solution.java @@ -2,7 +2,8 @@ class Solution { public int countSubarrays(int[] nums, int k) { int n = nums.length; int i = 0; - for (; nums[i] != k; ++i) {} + for (; nums[i] != k; ++i) { + } int[] cnt = new int[n << 1 | 1]; int ans = 1; int x = 0; diff --git a/solution/2500-2599/2574.Left and Right Sum Differences/Solution.c b/solution/2500-2599/2574.Left and Right Sum Differences/Solution.c index 3e8279b515177..f2068a7f47601 100644 --- a/solution/2500-2599/2574.Left and Right Sum Differences/Solution.c +++ b/solution/2500-2599/2574.Left and Right Sum Differences/Solution.c @@ -1,13 +1,13 @@ /** * Note: The returned array must be malloced, assume caller calls free(). */ -int *leftRigthDifference(int *nums, int numsSize, int *returnSize) { +int* leftRigthDifference(int* nums, int numsSize, int* returnSize) { int left = 0; int right = 0; for (int i = 0; i < numsSize; i++) { right += nums[i]; } - int *ans = malloc(sizeof(int) * numsSize); + int* ans = malloc(sizeof(int) * numsSize); for (int i = 0; i < numsSize; i++) { right -= nums[i]; ans[i] = abs(left - right); diff --git a/solution/2500-2599/2575.Find the Divisibility Array of a String/Solution.c b/solution/2500-2599/2575.Find the Divisibility Array of a String/Solution.c index 6f85d9551b983..b33340325be00 100644 --- a/solution/2500-2599/2575.Find the Divisibility Array of a String/Solution.c +++ b/solution/2500-2599/2575.Find the Divisibility Array of a String/Solution.c @@ -1,9 +1,9 @@ /** * Note: The returned array must be malloced, assume caller calls free(). */ -int *divisibilityArray(char *word, int m, int *returnSize) { +int* divisibilityArray(char* word, int m, int* returnSize) { int n = strlen(word); - int *ans = malloc(sizeof(int) * n); + int* ans = malloc(sizeof(int) * n); long long x = 0; for (int i = 0; i < n; i++) { x = (x * 10 + word[i] - '0') % m; diff --git a/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/Solution.cpp b/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/Solution.cpp index 1329c3fbb6374..9d3ac7ba3d1da 100644 --- a/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/Solution.cpp +++ b/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/Solution.cpp @@ -2,7 +2,7 @@ class Solution { public: int vowelStrings(vector& words, int left, int right) { auto check = [](char c) -> bool { - return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; + return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; }; int ans = 0; for (int i = left; i <= right; ++i) { diff --git a/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/Solution.java b/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/Solution.java index e16b5504f09b2..fbd756587e44c 100644 --- a/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/Solution.java +++ b/solution/2500-2599/2586.Count the Number of Vowel Strings in Range/Solution.java @@ -9,7 +9,7 @@ public int vowelStrings(String[] words, int left, int right) { } return ans; } - + private boolean check(char c) { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; } diff --git a/solution/2500-2599/2590.Design a Todo List/README.md b/solution/2500-2599/2590.Design a Todo List/README.md index e649aa9bd3102..de38610a92ce1 100644 --- a/solution/2500-2599/2590.Design a Todo List/README.md +++ b/solution/2500-2599/2590.Design a Todo List/README.md @@ -144,12 +144,12 @@ class TodoList { private Map> tasks = new HashMap<>(); public TodoList() { - } public int addTask(int userId, String taskDescription, int dueDate, List tags) { Task task = new Task(i++, taskDescription, dueDate, new HashSet<>(tags)); - tasks.computeIfAbsent(userId, k -> new TreeSet<>(Comparator.comparingInt(a -> a.dueDate))).add(task); + tasks.computeIfAbsent(userId, k -> new TreeSet<>(Comparator.comparingInt(a -> a.dueDate))) + .add(task); return task.taskId; } diff --git a/solution/2500-2599/2590.Design a Todo List/README_EN.md b/solution/2500-2599/2590.Design a Todo List/README_EN.md index bda00bf67fff7..2742c8ef0e20b 100644 --- a/solution/2500-2599/2590.Design a Todo List/README_EN.md +++ b/solution/2500-2599/2590.Design a Todo List/README_EN.md @@ -122,12 +122,12 @@ class TodoList { private Map> tasks = new HashMap<>(); public TodoList() { - } public int addTask(int userId, String taskDescription, int dueDate, List tags) { Task task = new Task(i++, taskDescription, dueDate, new HashSet<>(tags)); - tasks.computeIfAbsent(userId, k -> new TreeSet<>(Comparator.comparingInt(a -> a.dueDate))).add(task); + tasks.computeIfAbsent(userId, k -> new TreeSet<>(Comparator.comparingInt(a -> a.dueDate))) + .add(task); return task.taskId; } diff --git a/solution/2500-2599/2590.Design a Todo List/Solution.java b/solution/2500-2599/2590.Design a Todo List/Solution.java index 3e3e562c37393..e90401a6ebf7f 100644 --- a/solution/2500-2599/2590.Design a Todo List/Solution.java +++ b/solution/2500-2599/2590.Design a Todo List/Solution.java @@ -18,12 +18,12 @@ class TodoList { private Map> tasks = new HashMap<>(); public TodoList() { - } public int addTask(int userId, String taskDescription, int dueDate, List tags) { Task task = new Task(i++, taskDescription, dueDate, new HashSet<>(tags)); - tasks.computeIfAbsent(userId, k -> new TreeSet<>(Comparator.comparingInt(a -> a.dueDate))).add(task); + tasks.computeIfAbsent(userId, k -> new TreeSet<>(Comparator.comparingInt(a -> a.dueDate))) + .add(task); return task.taskId; } diff --git a/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution.java b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution.java index 9606263aafb5a..02b8475c5e50f 100644 --- a/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution.java +++ b/solution/2500-2599/2593.Find Score of an Array After Marking All Elements/Solution.java @@ -2,7 +2,8 @@ class Solution { public long findScore(int[] nums) { int n = nums.length; boolean[] vis = new boolean[n]; - PriorityQueue q = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); + PriorityQueue q + = new PriorityQueue<>((a, b) -> a[0] == b[0] ? a[1] - b[1] : a[0] - b[0]); for (int i = 0; i < n; ++i) { q.offer(new int[] {nums[i], i}); } diff --git a/solution/2500-2599/2594.Minimum Time to Repair Cars/Solution.cpp b/solution/2500-2599/2594.Minimum Time to Repair Cars/Solution.cpp index 1234488f4b234..ef7128d62c229 100644 --- a/solution/2500-2599/2594.Minimum Time to Repair Cars/Solution.cpp +++ b/solution/2500-2599/2594.Minimum Time to Repair Cars/Solution.cpp @@ -13,7 +13,7 @@ class Solution { } else { left = mid + 1; } - } + } return left; } }; \ No newline at end of file diff --git a/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README.md b/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README.md index 31ace9297d626..65482408ef523 100644 --- a/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README.md +++ b/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README.md @@ -92,7 +92,7 @@ class Solution { for (int x : nums) { ++cnt[(x % value + value) % value]; } - for (int i = 0;;++i) { + for (int i = 0;; ++i) { if (cnt[i % value]-- == 0) { return i; } diff --git a/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README_EN.md b/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README_EN.md index 718863b65dd83..e37a236eb8c66 100644 --- a/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README_EN.md +++ b/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/README_EN.md @@ -76,7 +76,7 @@ class Solution { for (int x : nums) { ++cnt[(x % value + value) % value]; } - for (int i = 0;;++i) { + for (int i = 0;; ++i) { if (cnt[i % value]-- == 0) { return i; } diff --git a/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/Solution.java b/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/Solution.java index 6800e26363dbf..ad6de969d2ceb 100644 --- a/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/Solution.java +++ b/solution/2500-2599/2598.Smallest Missing Non-negative Integer After Operations/Solution.java @@ -4,7 +4,7 @@ public int findSmallestInteger(int[] nums, int value) { for (int x : nums) { ++cnt[(x % value + value) % value]; } - for (int i = 0;;++i) { + for (int i = 0;; ++i) { if (cnt[i % value]-- == 0) { return i; } diff --git a/solution/2600-2699/2600.K Items With the Maximum Sum/README.md b/solution/2600-2699/2600.K Items With the Maximum Sum/README.md index 64ca11a95d456..78350d8cd008b 100644 --- a/solution/2600-2699/2600.K Items With the Maximum Sum/README.md +++ b/solution/2600-2699/2600.K Items With the Maximum Sum/README.md @@ -135,6 +135,27 @@ func kItemsWithMaximumSum(numOnes int, numZeros int, numNegOnes int, k int) int } ``` +### **TypeScript** + +```ts +function kItemsWithMaximumSum( + numOnes: number, + numZeros: number, + numNegOnes: number, + k: number, +): number { + if (numOnes >= k) { + return k; + } + k -= numOnes; + if (numZeros >= k) { + return numOnes; + } + k -= numZeros; + return numOnes - k; +} +``` + ### **...** ``` diff --git a/solution/2600-2699/2600.K Items With the Maximum Sum/README_EN.md b/solution/2600-2699/2600.K Items With the Maximum Sum/README_EN.md index 96fa6638bf90a..3b141a1a8ef9b 100644 --- a/solution/2600-2699/2600.K Items With the Maximum Sum/README_EN.md +++ b/solution/2600-2699/2600.K Items With the Maximum Sum/README_EN.md @@ -116,6 +116,27 @@ func kItemsWithMaximumSum(numOnes int, numZeros int, numNegOnes int, k int) int } ``` +### **TypeScript** + +```ts +function kItemsWithMaximumSum( + numOnes: number, + numZeros: number, + numNegOnes: number, + k: number, +): number { + if (numOnes >= k) { + return k; + } + k -= numOnes; + if (numZeros >= k) { + return numOnes; + } + k -= numZeros; + return numOnes - k; +} +``` + ### **...** ``` diff --git a/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.ts b/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.ts new file mode 100644 index 0000000000000..c49658bc369e6 --- /dev/null +++ b/solution/2600-2699/2600.K Items With the Maximum Sum/Solution.ts @@ -0,0 +1,16 @@ +function kItemsWithMaximumSum( + numOnes: number, + numZeros: number, + numNegOnes: number, + k: number, +): number { + if (numOnes >= k) { + return k; + } + k -= numOnes; + if (numZeros >= k) { + return numOnes; + } + k -= numZeros; + return numOnes - k; +} diff --git a/solution/2600-2699/2601.Prime Subtraction Operation/README.md b/solution/2600-2699/2601.Prime Subtraction Operation/README.md index 2ee275fc91f95..bba9dd1303b11 100644 --- a/solution/2600-2699/2601.Prime Subtraction Operation/README.md +++ b/solution/2600-2699/2601.Prime Subtraction Operation/README.md @@ -211,6 +211,51 @@ func primeSubOperation(nums []int) bool { } ``` +### **TypeScript** + +```ts +function primeSubOperation(nums: number[]): boolean { + const p: number[] = []; + for (let i = 2; i <= 1000; ++i) { + let ok = true; + for (const j of p) { + if (i % j === 0) { + ok = false; + break; + } + } + if (ok) { + p.push(i); + } + } + const search = (x: number): number => { + let l = 0; + let r = p.length; + while (l < r) { + const mid = (l + r) >> 1; + if (p[mid] > x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + const n = nums.length; + for (let i = n - 2; i >= 0; --i) { + if (nums[i] < nums[i + 1]) { + continue; + } + const j = search(nums[i] - nums[i + 1]); + if (j === p.length || p[j] >= nums[i]) { + return false; + } + nums[i] -= p[j]; + } + return true; +} +``` + ### **...** ``` diff --git a/solution/2600-2699/2601.Prime Subtraction Operation/README_EN.md b/solution/2600-2699/2601.Prime Subtraction Operation/README_EN.md index 24437ef24c4c7..dd6b9cd9e8de1 100644 --- a/solution/2600-2699/2601.Prime Subtraction Operation/README_EN.md +++ b/solution/2600-2699/2601.Prime Subtraction Operation/README_EN.md @@ -190,6 +190,51 @@ func primeSubOperation(nums []int) bool { } ``` +### **TypeScript** + +```ts +function primeSubOperation(nums: number[]): boolean { + const p: number[] = []; + for (let i = 2; i <= 1000; ++i) { + let ok = true; + for (const j of p) { + if (i % j === 0) { + ok = false; + break; + } + } + if (ok) { + p.push(i); + } + } + const search = (x: number): number => { + let l = 0; + let r = p.length; + while (l < r) { + const mid = (l + r) >> 1; + if (p[mid] > x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + const n = nums.length; + for (let i = n - 2; i >= 0; --i) { + if (nums[i] < nums[i + 1]) { + continue; + } + const j = search(nums[i] - nums[i + 1]); + if (j === p.length || p[j] >= nums[i]) { + return false; + } + nums[i] -= p[j]; + } + return true; +} +``` + ### **...** ``` diff --git a/solution/2600-2699/2601.Prime Subtraction Operation/Solution.java b/solution/2600-2699/2601.Prime Subtraction Operation/Solution.java index cf5f2dcdd2abf..c4650880306eb 100644 --- a/solution/2600-2699/2601.Prime Subtraction Operation/Solution.java +++ b/solution/2600-2699/2601.Prime Subtraction Operation/Solution.java @@ -26,7 +26,7 @@ public boolean primeSubOperation(int[] nums) { } return true; } - + private int search(List nums, int x) { int l = 0, r = nums.size(); while (l < r) { diff --git a/solution/2600-2699/2601.Prime Subtraction Operation/Solution.ts b/solution/2600-2699/2601.Prime Subtraction Operation/Solution.ts new file mode 100644 index 0000000000000..29bae9f65df5d --- /dev/null +++ b/solution/2600-2699/2601.Prime Subtraction Operation/Solution.ts @@ -0,0 +1,40 @@ +function primeSubOperation(nums: number[]): boolean { + const p: number[] = []; + for (let i = 2; i <= 1000; ++i) { + let ok = true; + for (const j of p) { + if (i % j === 0) { + ok = false; + break; + } + } + if (ok) { + p.push(i); + } + } + const search = (x: number): number => { + let l = 0; + let r = p.length; + while (l < r) { + const mid = (l + r) >> 1; + if (p[mid] > x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + const n = nums.length; + for (let i = n - 2; i >= 0; --i) { + if (nums[i] < nums[i + 1]) { + continue; + } + const j = search(nums[i] - nums[i + 1]); + if (j === p.length || p[j] >= nums[i]) { + return false; + } + nums[i] -= p[j]; + } + return true; +} diff --git a/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README.md b/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README.md index 814c702a41bbc..44be75608106c 100644 --- a/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README.md +++ b/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README.md @@ -179,6 +179,41 @@ func minOperations(nums []int, queries []int) (ans []int64) { } ``` +### **TypeScript** + +```ts +function minOperations(nums: number[], queries: number[]): number[] { + nums.sort((a, b) => a - b); + const n = nums.length; + const s: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + const search = (x: number): number => { + let l = 0; + let r = n; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + const ans: number[] = []; + for (const x of queries) { + const i = search(x + 1); + let t = s[n] - s[i] - (n - i) * x; + const j = search(x); + t += x * j - s[j]; + ans.push(t); + } + return ans; +} +``` + ### **...** ``` diff --git a/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README_EN.md b/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README_EN.md index ea7a514489f5f..da5caf52954b5 100644 --- a/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README_EN.md +++ b/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/README_EN.md @@ -157,6 +157,41 @@ func minOperations(nums []int, queries []int) (ans []int64) { } ``` +### **TypeScript** + +```ts +function minOperations(nums: number[], queries: number[]): number[] { + nums.sort((a, b) => a - b); + const n = nums.length; + const s: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + const search = (x: number): number => { + let l = 0; + let r = n; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + const ans: number[] = []; + for (const x of queries) { + const i = search(x + 1); + let t = s[n] - s[i] - (n - i) * x; + const j = search(x); + t += x * j - s[j]; + ans.push(t); + } + return ans; +} +``` + ### **...** ``` diff --git a/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/Solution.java b/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/Solution.java index a56d69ae6990e..4e1391f0b6ca3 100644 --- a/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/Solution.java +++ b/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/Solution.java @@ -16,7 +16,7 @@ public List minOperations(int[] nums, int[] queries) { } return ans; } - + private int search(int[] nums, int x) { int l = 0, r = nums.length; while (l < r) { diff --git a/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/Solution.ts b/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/Solution.ts new file mode 100644 index 0000000000000..fe9d65f3a6cb5 --- /dev/null +++ b/solution/2600-2699/2602.Minimum Operations to Make All Array Elements Equal/Solution.ts @@ -0,0 +1,30 @@ +function minOperations(nums: number[], queries: number[]): number[] { + nums.sort((a, b) => a - b); + const n = nums.length; + const s: number[] = new Array(n + 1).fill(0); + for (let i = 0; i < n; ++i) { + s[i + 1] = s[i] + nums[i]; + } + const search = (x: number): number => { + let l = 0; + let r = n; + while (l < r) { + const mid = (l + r) >> 1; + if (nums[mid] >= x) { + r = mid; + } else { + l = mid + 1; + } + } + return l; + }; + const ans: number[] = []; + for (const x of queries) { + const i = search(x + 1); + let t = s[n] - s[i] - (n - i) * x; + const j = search(x); + t += x * j - s[j]; + ans.push(t); + } + return ans; +} diff --git a/solution/2600-2699/2603.Collect Coins in a Tree/README.md b/solution/2600-2699/2603.Collect Coins in a Tree/README.md index 784ff5236fc29..1e52ff1e4d896 100644 --- a/solution/2600-2699/2603.Collect Coins in a Tree/README.md +++ b/solution/2600-2699/2603.Collect Coins in a Tree/README.md @@ -272,6 +272,56 @@ func collectTheCoins(coins []int, edges [][]int) int { } ``` +### **TypeScript** + +```ts +function collectTheCoins(coins: number[], edges: number[][]): number { + const n = coins.length; + const g: Set[] = new Array(n).fill(0).map(() => new Set()); + for (const [a, b] of edges) { + g[a].add(b); + g[b].add(a); + } + let q: number[] = []; + for (let i = 0; i < n; ++i) { + if (coins[i] === 0 && g[i].size === 1) { + q.push(i); + } + } + while (q.length) { + const i = q.pop()!; + for (const j of g[i]) { + g[j].delete(i); + if (coins[j] === 0 && g[j].size === 1) { + q.push(j); + } + } + g[i].clear(); + } + q = []; + for (let k = 0; k < 2; ++k) { + for (let i = 0; i < n; ++i) { + if (g[i].size === 1) { + q.push(i); + } + } + for (const i of q) { + for (const j of g[i]) { + g[j].delete(i); + } + g[i].clear(); + } + } + let ans = 0; + for (const [a, b] of edges) { + if (g[a].size > 0 && g[b].size > 0) { + ans += 2; + } + } + return ans; +} +``` + ### **...** ``` diff --git a/solution/2600-2699/2603.Collect Coins in a Tree/README_EN.md b/solution/2600-2699/2603.Collect Coins in a Tree/README_EN.md index be66e2c9afe1b..f1769950cd1c8 100644 --- a/solution/2600-2699/2603.Collect Coins in a Tree/README_EN.md +++ b/solution/2600-2699/2603.Collect Coins in a Tree/README_EN.md @@ -246,6 +246,56 @@ func collectTheCoins(coins []int, edges [][]int) int { } ``` +### **TypeScript** + +```ts +function collectTheCoins(coins: number[], edges: number[][]): number { + const n = coins.length; + const g: Set[] = new Array(n).fill(0).map(() => new Set()); + for (const [a, b] of edges) { + g[a].add(b); + g[b].add(a); + } + let q: number[] = []; + for (let i = 0; i < n; ++i) { + if (coins[i] === 0 && g[i].size === 1) { + q.push(i); + } + } + while (q.length) { + const i = q.pop()!; + for (const j of g[i]) { + g[j].delete(i); + if (coins[j] === 0 && g[j].size === 1) { + q.push(j); + } + } + g[i].clear(); + } + q = []; + for (let k = 0; k < 2; ++k) { + for (let i = 0; i < n; ++i) { + if (g[i].size === 1) { + q.push(i); + } + } + for (const i of q) { + for (const j of g[i]) { + g[j].delete(i); + } + g[i].clear(); + } + } + let ans = 0; + for (const [a, b] of edges) { + if (g[a].size > 0 && g[b].size > 0) { + ans += 2; + } + } + return ans; +} +``` + ### **...** ``` diff --git a/solution/2600-2699/2603.Collect Coins in a Tree/Solution.ts b/solution/2600-2699/2603.Collect Coins in a Tree/Solution.ts new file mode 100644 index 0000000000000..d0a87842001dc --- /dev/null +++ b/solution/2600-2699/2603.Collect Coins in a Tree/Solution.ts @@ -0,0 +1,45 @@ +function collectTheCoins(coins: number[], edges: number[][]): number { + const n = coins.length; + const g: Set[] = new Array(n).fill(0).map(() => new Set()); + for (const [a, b] of edges) { + g[a].add(b); + g[b].add(a); + } + let q: number[] = []; + for (let i = 0; i < n; ++i) { + if (coins[i] === 0 && g[i].size === 1) { + q.push(i); + } + } + while (q.length) { + const i = q.pop()!; + for (const j of g[i]) { + g[j].delete(i); + if (coins[j] === 0 && g[j].size === 1) { + q.push(j); + } + } + g[i].clear(); + } + q = []; + for (let k = 0; k < 2; ++k) { + for (let i = 0; i < n; ++i) { + if (g[i].size === 1) { + q.push(i); + } + } + for (const i of q) { + for (const j of g[i]) { + g[j].delete(i); + } + g[i].clear(); + } + } + let ans = 0; + for (const [a, b] of edges) { + if (g[a].size > 0 && g[b].size > 0) { + ans += 2; + } + } + return ans; +}