diff --git a/solution/1000-1099/1094.Car Pooling/README.md b/solution/1000-1099/1094.Car Pooling/README.md index 1d8eee89ff025..16eb7a31230e3 100644 --- a/solution/1000-1099/1094.Car Pooling/README.md +++ b/solution/1000-1099/1094.Car Pooling/README.md @@ -46,9 +46,9 @@ **方法一:差分数组** -我们可以利用差分数组的思想,将每个行程的乘客数加到起点,减去终点,最后遍历差分数组,若当前乘客数大于容量,则返回 `false`,否则返回 `true`。 +我们可以利用差分数组的思想,将每个行程的乘客数加到起点,减去终点,最后我们只需要判断差分数组的前缀和是否都不大于车的最大载客量即可。 -时间复杂度 $O(n),ドル空间复杂度 $O(m)$。其中 $n$ 和 $m$ 分别为行程数和行程中的最大终点。 +时间复杂度 $O(n),ドル空间复杂度 $O(M)$。其中 $n$ 是行程数,而 $M$ 是行程中最大的终点,本题中 $M \le 1000$。 @@ -59,7 +59,8 @@ ```python class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: - d = [0] * 1001 + mx = max(e[2] for e in trips) + d = [0] * (mx + 1) for x, f, t in trips: d[f] += x d[t] -= x @@ -145,7 +146,8 @@ func carPooling(trips [][]int, capacity int) bool { * @return {boolean} */ var carPooling = function (trips, capacity) { - const d = new Array(1001).fill(0); + const mx = Math.max(...trips.map(([, , t]) => t)); + const d = Array(mx + 1).fill(0); for (const [x, f, t] of trips) { d[f] += x; d[t] -= x; @@ -165,7 +167,8 @@ var carPooling = function (trips, capacity) { ```ts function carPooling(trips: number[][], capacity: number): boolean { - const d = new Array(1001).fill(0); + const mx = Math.max(...trips.map(([, , t]) => t)); + const d = Array(mx + 1).fill(0); for (const [x, f, t] of trips) { d[f] += x; d[t] -= x; @@ -181,6 +184,56 @@ function carPooling(trips: number[][], capacity: number): boolean { } ``` +### **C#** + +```cs +public class Solution { + public bool CarPooling(int[][] trips, int capacity) { + int mx = trips.Max(x => x[2]); + int[] d = new int[mx + 1]; + foreach (var trip in trips) { + int x = trip[0], f = trip[1], t = trip[2]; + d[f] += x; + d[t] -= x; + } + int s = 0; + foreach (var x in d) { + s += x; + if (s> capacity) { + return false; + } + } + return true; + } +} +``` + +### **Rust** + +```rust +impl Solution { + pub fn car_pooling(trips: Vec>, capacity: i32) -> bool { + let mx = trips + .iter() + .map(|e| e[2]) + .max() + .unwrap_or(0) as usize; + let mut d = vec![0; mx + 1]; + for trip in &trips { + let (x, f, t) = (trip[0], trip[1] as usize, trip[2] as usize); + d[f] += x; + d[t] -= x; + } + d.iter() + .scan(0, |acc, &x| { + *acc += x; + Some(*acc) + }) + .all(|s| s <= capacity) + } +} +``` + ### **...** ``` diff --git a/solution/1000-1099/1094.Car Pooling/README_EN.md b/solution/1000-1099/1094.Car Pooling/README_EN.md index 1a12ee3415189..b6ccc8d9e1604 100644 --- a/solution/1000-1099/1094.Car Pooling/README_EN.md +++ b/solution/1000-1099/1094.Car Pooling/README_EN.md @@ -38,6 +38,12 @@ ## Solutions +**Solution 1: Difference Array** + +We can use the idea of a difference array, adding the number of passengers to the starting point of each trip and subtracting from the end point. Finally, we just need to check whether the prefix sum of the difference array does not exceed the maximum passenger capacity of the car. + +The time complexity is $O(n),ドル and the space complexity is $O(M)$. Here, $n$ is the number of trips, and $M$ is the maximum end point in the trips. In this problem, $M \le 1000$. + ### **Python3** @@ -45,7 +51,8 @@ ```python class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: - d = [0] * 1001 + mx = max(e[2] for e in trips) + d = [0] * (mx + 1) for x, f, t in trips: d[f] += x d[t] -= x @@ -129,7 +136,8 @@ func carPooling(trips [][]int, capacity int) bool { * @return {boolean} */ var carPooling = function (trips, capacity) { - const d = new Array(1001).fill(0); + const mx = Math.max(...trips.map(([, , t]) => t)); + const d = Array(mx + 1).fill(0); for (const [x, f, t] of trips) { d[f] += x; d[t] -= x; @@ -149,7 +157,8 @@ var carPooling = function (trips, capacity) { ```ts function carPooling(trips: number[][], capacity: number): boolean { - const d = new Array(1001).fill(0); + const mx = Math.max(...trips.map(([, , t]) => t)); + const d = Array(mx + 1).fill(0); for (const [x, f, t] of trips) { d[f] += x; d[t] -= x; @@ -165,6 +174,56 @@ function carPooling(trips: number[][], capacity: number): boolean { } ``` +### **C#** + +```cs +public class Solution { + public bool CarPooling(int[][] trips, int capacity) { + int mx = trips.Max(x => x[2]); + int[] d = new int[mx + 1]; + foreach (var trip in trips) { + int x = trip[0], f = trip[1], t = trip[2]; + d[f] += x; + d[t] -= x; + } + int s = 0; + foreach (var x in d) { + s += x; + if (s> capacity) { + return false; + } + } + return true; + } +} +``` + +### **Rust** + +```rust +impl Solution { + pub fn car_pooling(trips: Vec>, capacity: i32) -> bool { + let mx = trips + .iter() + .map(|e| e[2]) + .max() + .unwrap_or(0) as usize; + let mut d = vec![0; mx + 1]; + for trip in &trips { + let (x, f, t) = (trip[0], trip[1] as usize, trip[2] as usize); + d[f] += x; + d[t] -= x; + } + d.iter() + .scan(0, |acc, &x| { + *acc += x; + Some(*acc) + }) + .all(|s| s <= capacity) + } +} +``` + ### **...** ``` diff --git a/solution/1000-1099/1094.Car Pooling/Solution.cs b/solution/1000-1099/1094.Car Pooling/Solution.cs new file mode 100644 index 0000000000000..3cefdc57eb99f --- /dev/null +++ b/solution/1000-1099/1094.Car Pooling/Solution.cs @@ -0,0 +1,19 @@ +public class Solution { + public bool CarPooling(int[][] trips, int capacity) { + int mx = trips.Max(x => x[2]); + int[] d = new int[mx + 1]; + foreach (var trip in trips) { + int x = trip[0], f = trip[1], t = trip[2]; + d[f] += x; + d[t] -= x; + } + int s = 0; + foreach (var x in d) { + s += x; + if (s> capacity) { + return false; + } + } + return true; + } +} \ No newline at end of file diff --git a/solution/1000-1099/1094.Car Pooling/Solution.go b/solution/1000-1099/1094.Car Pooling/Solution.go index 95c9c3d009eab..1ee5596dd56c8 100644 --- a/solution/1000-1099/1094.Car Pooling/Solution.go +++ b/solution/1000-1099/1094.Car Pooling/Solution.go @@ -1,5 +1,6 @@ func carPooling(trips [][]int, capacity int) bool { - d := [1001]int{} + mx := slices.Max(trips, func(i int) int { return trips[i][2] }) + d := make([]int, mx+1) for _, trip := range trips { x, f, t := trip[0], trip[1], trip[2] d[f] += x diff --git a/solution/1000-1099/1094.Car Pooling/Solution.js b/solution/1000-1099/1094.Car Pooling/Solution.js index 6f0cf9bd6b9ae..469018a01d916 100644 --- a/solution/1000-1099/1094.Car Pooling/Solution.js +++ b/solution/1000-1099/1094.Car Pooling/Solution.js @@ -4,7 +4,8 @@ * @return {boolean} */ var carPooling = function (trips, capacity) { - const d = new Array(1001).fill(0); + const mx = Math.max(...trips.map(([, , t]) => t)); + const d = Array(mx + 1).fill(0); for (const [x, f, t] of trips) { d[f] += x; d[t] -= x; diff --git a/solution/1000-1099/1094.Car Pooling/Solution.py b/solution/1000-1099/1094.Car Pooling/Solution.py index b2e9e19504b99..a21c5887681fb 100644 --- a/solution/1000-1099/1094.Car Pooling/Solution.py +++ b/solution/1000-1099/1094.Car Pooling/Solution.py @@ -1,6 +1,7 @@ class Solution: def carPooling(self, trips: List[List[int]], capacity: int) -> bool: - d = [0] * 1001 + mx = max(e[2] for e in trips) + d = [0] * (mx + 1) for x, f, t in trips: d[f] += x d[t] -= x diff --git a/solution/1000-1099/1094.Car Pooling/Solution.rs b/solution/1000-1099/1094.Car Pooling/Solution.rs new file mode 100644 index 0000000000000..c30df69bcf6d2 --- /dev/null +++ b/solution/1000-1099/1094.Car Pooling/Solution.rs @@ -0,0 +1,21 @@ +impl Solution { + pub fn car_pooling(trips: Vec>, capacity: i32) -> bool { + let mx = trips + .iter() + .map(|e| e[2]) + .max() + .unwrap_or(0) as usize; + let mut d = vec![0; mx + 1]; + for trip in &trips { + let (x, f, t) = (trip[0], trip[1] as usize, trip[2] as usize); + d[f] += x; + d[t] -= x; + } + d.iter() + .scan(0, |acc, &x| { + *acc += x; + Some(*acc) + }) + .all(|s| s <= capacity) + } +} diff --git a/solution/1000-1099/1094.Car Pooling/Solution.ts b/solution/1000-1099/1094.Car Pooling/Solution.ts index 9c42db6c3d9ea..a1f5f21254953 100644 --- a/solution/1000-1099/1094.Car Pooling/Solution.ts +++ b/solution/1000-1099/1094.Car Pooling/Solution.ts @@ -1,5 +1,6 @@ function carPooling(trips: number[][], capacity: number): boolean { - const d = new Array(1001).fill(0); + const mx = Math.max(...trips.map(([, , t]) => t)); + const d = Array(mx + 1).fill(0); for (const [x, f, t] of trips) { d[f] += x; d[t] -= x; diff --git a/solution/1000-1099/1099.Two Sum Less Than K/README_EN.md b/solution/1000-1099/1099.Two Sum Less Than K/README_EN.md index 197f8609d4fd2..07bd5c9e19c87 100644 --- a/solution/1000-1099/1099.Two Sum Less Than K/README_EN.md +++ b/solution/1000-1099/1099.Two Sum Less Than K/README_EN.md @@ -34,6 +34,26 @@ ## Solutions +**Solution 1: Sorting + Binary Search** + +We can first sort the array $nums,ドル and initialize the answer as $-1$. + +Next, we enumerate each element $nums[i]$ in the array, and find the maximum $nums[j]$ in the array that satisfies $nums[j] + nums[i] < k$. Here, we can use binary search to speed up the search process. If we find such a $nums[j],ドル then we can update the answer, i.e., $ans = \max(ans, nums[i] + nums[j])$. + +After the enumeration ends, return the answer. + +The time complexity is $O(n \times \log n),ドル and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $nums$. + +**Solution 2: Sorting + Two Pointers** + +Similar to Method 1, we can first sort the array $nums,ドル and initialize the answer as $-1$. + +Next, we use two pointers $i$ and $j$ to point to the left and right ends of the array, respectively. Each time we judge whether $s = nums[i] + nums[j]$ is less than $k$. If it is less than $k,ドル then we can update the answer, i.e., $ans = \max(ans, s),ドル and move $i$ one step to the right, otherwise move $j$ one step to the left. + +After the enumeration ends, return the answer. + +The time complexity is $O(n \times \log n),ドル and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $nums$. + ### **Python3** diff --git a/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README_EN.md b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README_EN.md index 08c1ac57c01f9..622f07e142c33 100644 --- a/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README_EN.md +++ b/solution/1100-1199/1100.Find K-Length Substrings With No Repeated Characters/README_EN.md @@ -34,6 +34,18 @@ ## Solutions +**Solution 1: Two Pointers + Counter** + +We observe that all characters are lowercase letters, so there are at most 26ドル$ different characters. Therefore, if $k> 26$ or $k> n,ドル it is impossible to find any substring of length $k$ without repeated characters, and we can directly return 0ドル$. + +Next, we use two pointers $j$ and $i$ to maintain a sliding window, where $j$ is the left endpoint of the sliding window, $i$ is the right endpoint of the sliding window, and a counter $cnt$ is used to count the number of occurrences of each character in the sliding window. + +We traverse the string $s,ドル each time adding $s[i]$ to the sliding window, i.e., $cnt[s[i]]++$. If at this time $cnt[s[i]]> 1$ or $i - j + 1> k,ドル then we loop to remove $s[j]$ from the sliding window, i.e., $cnt[s[j]]--,ドル and move $j$ to the right. If after moving $j$ to the right, the window size $i - j + 1$ is exactly equal to $k,ドル it means that the string in the sliding window is a substring that meets the requirements of the problem, and we increment the result by one. + +After the traversal ends, we can get the number of all substrings that meet the requirements of the problem. + +The time complexity is $O(n),ドル and the space complexity is $O(C)$. Here, $n$ is the length of the string $s,ドル and $C$ is the size of the character set. In this problem, $C = 26$. + ### **Python3** diff --git a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README_EN.md b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README_EN.md index d52345d1d5cb1..07e6d10877a0a 100644 --- a/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README_EN.md +++ b/solution/1100-1199/1101.The Earliest Moment When Everyone Become Friends/README_EN.md @@ -49,7 +49,13 @@ The sixth event occurs at timestamp = 20190301, and after 0 and 3 become friends ## Solutions -Union find. +**Solution 1: Sorting + Union-Find** + +We sort all the logs in ascending order by timestamp, then traverse the sorted logs. Using a union-find set, we check whether the two people in the current log are already friends. If they are not friends, we merge them into one friend circle, until everyone is in one friend circle, then return the timestamp of the current log. + +If we have traversed all the logs and not everyone is in one friend circle, then return $-1$. + +The time complexity is $O(n \times \log n),ドル and the space complexity is $O(n)$. Here, $n$ is the number of logs. diff --git a/solution/1100-1199/1102.Path With Maximum Minimum Value/README_EN.md b/solution/1100-1199/1102.Path With Maximum Minimum Value/README_EN.md index 0414594b74234..b090675c93c93 100644 --- a/solution/1100-1199/1102.Path With Maximum Minimum Value/README_EN.md +++ b/solution/1100-1199/1102.Path With Maximum Minimum Value/README_EN.md @@ -47,6 +47,14 @@ ## Solutions +**Solution 1: Sorting + Union-Find** + +First, we construct a triplet $(v, i, j)$ for each element in the matrix, where $v$ represents the element value, and $i$ and $j$ represent the row and column of the element in the matrix, respectively. Then we sort these triplets in descending order by element value and store them in a list $q$. + +Next, we take out the triplets from $q$ in order, use the corresponding element value as the score of the path, and mark the position as visited. Then we check the four adjacent positions (up, down, left, and right) of this position. If an adjacent position has been visited, we merge this position with the current position. If we find that the position $(0, 0)$ and the position $(m - 1, n - 1)$ have been merged, we can directly return the score of the current path as the answer. + +The time complexity is $O(m \times n \times (\log (m \times n) + \alpha(m \times n))),ドル where $m$ and $n$ are the number of rows and columns of the matrix, respectively. + ### **Python3** diff --git a/solution/1100-1199/1103.Distribute Candies to People/README_EN.md b/solution/1100-1199/1103.Distribute Candies to People/README_EN.md index 172377aaa909e..79f3d48c29ccd 100644 --- a/solution/1100-1199/1103.Distribute Candies to People/README_EN.md +++ b/solution/1100-1199/1103.Distribute Candies to People/README_EN.md @@ -49,6 +49,12 @@ On the fourth turn, ans[0] += 4, and the final array is [5,2,3]. ## Solutions +**Solution 1: Simulation** + +We can directly simulate the process of each person receiving candies, following the rules described in the problem. + +The time complexity is $O(\max(\sqrt{candies}, num\_people)),ドル and the space complexity is $O(num\_people)$. Here, $candies$ is the number of candies. + ### **Python3** diff --git a/solution/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README_EN.md b/solution/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README_EN.md index fac52b403b44c..15d7d4546058c 100644 --- a/solution/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README_EN.md +++ b/solution/1100-1199/1104.Path In Zigzag Labelled Binary Tree/README_EN.md @@ -36,6 +36,14 @@ ## Solutions +**Solution 1: Mathematics** + +For a complete binary tree, the number of nodes in the $i$th row is 2ドル^{i-1},ドル and the range of node labels in the $i$th row is $[2^{i-1}, 2^i - 1]$. In the problem, for odd-numbered rows, the nodes are labeled from left to right, while for even-numbered rows, the nodes are labeled from right to left. Therefore, for the node $label$ in the $i$th row, its complementary node label is 2ドル^{i-1} + 2^i - 1 - label$. So the actual parent node label of node $label$ is $(2^{i-1} + 2^i - 1 - label) / 2$. We can find the path from the root node to node $label$ by continuously finding the complementary node label and the parent node label until we reach the root node. + +Finally, we need to reverse the path, because the problem requires the path from the root node to node $label$. + +The time complexity is $O(\log n),ドル where $n$ is the label of the node. Ignoring the space consumption of the answer, the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1100-1199/1105.Filling Bookcase Shelves/README_EN.md b/solution/1100-1199/1105.Filling Bookcase Shelves/README_EN.md index 7ca80266e58a1..efbcc2b711eb1 100644 --- a/solution/1100-1199/1105.Filling Bookcase Shelves/README_EN.md +++ b/solution/1100-1199/1105.Filling Bookcase Shelves/README_EN.md @@ -47,6 +47,19 @@ Notice that book number 2 does not have to be on the first shelf. ## Solutions +**Solution 1: Dynamic Programming** + +We define $f[i]$ as the minimum height for placing the first $i$ books, initially $f[0] = 0,ドル and the answer is $f[n]$. + +Consider $f[i],ドル the last book is $books[i - 1],ドル its thickness is $w,ドル and its height is $h$. + +- If this book is placed on a new layer alone, then $f[i] = f[i - 1] + h$; +- If this book can be placed on the same layer with the last few books in front, we enumerate the first book $books[j-1]$ on the same layer from back to front, where $j \in [1, i - 1],ドル accumulate the thickness of the book to $w,ドル if $w> shelfWidth,ドル it means that $books[j-1]$ can no longer be placed on the same layer with $books[i-1],ドル stop enumeration; otherwise, we update the maximum height $h = \max(h, books[j-1][1])$ of the current layer, then $f[i] = \min(f[i], f[j - 1] + h)$. + +The final answer is $f[n]$. + +The time complexity is $O(n^2),ドル and the space complexity is $O(n)$. Here, $n$ is the length of the array $books$. + ### **Python3** diff --git a/solution/1100-1199/1106.Parsing A Boolean Expression/README.md b/solution/1100-1199/1106.Parsing A Boolean Expression/README.md index 41f4fa50ea2cf..eb6d0f939bbe7 100644 --- a/solution/1100-1199/1106.Parsing A Boolean Expression/README.md +++ b/solution/1100-1199/1106.Parsing A Boolean Expression/README.md @@ -75,7 +75,7 @@ 遍历完表达式 `expression` 后,栈中只剩下一个字符,如果是 `'t'`,返回 `true`,否则返回 `false`。 -时间复杂度 $O(n),ドル空间复杂度 $O(n)$。 +时间复杂度 $O(n),ドル空间复杂度 $O(n)$。其中 $n$ 是表达式 `expression` 的长度。 diff --git a/solution/1100-1199/1106.Parsing A Boolean Expression/README_EN.md b/solution/1100-1199/1106.Parsing A Boolean Expression/README_EN.md index 7994b21ad111a..ae3074d882886 100644 --- a/solution/1100-1199/1106.Parsing A Boolean Expression/README_EN.md +++ b/solution/1100-1199/1106.Parsing A Boolean Expression/README_EN.md @@ -58,6 +58,19 @@ Then, evaluate !(f) --> NOT false --> true. We return true. ## Solutions +**Solution 1: Stack** + +For this type of expression parsing problem, we can use a stack to assist. + +We traverse the expression `expression` from left to right. For each character $c$ we encounter: + +- If $c$ is one of `"tf!&|"`, we push it directly onto the stack; +- If $c$ is a right parenthesis `')'`, we pop elements from the stack until we encounter an operator `'!'`, `'&'`, or `'|'`. During this process, we use variables $t$ and $f$ to record the number of `'t'` and `'f'` characters popped from the stack. Finally, based on the number of characters popped and the operator, we calculate a new character `'t'` or `'f'` and push it onto the stack. + +After traversing the expression `expression`, there is only one character left in the stack. If it is `'t'`, return `true`, otherwise return `false`. + +The time complexity is $O(n),ドル and the space complexity is $O(n)$. Here, $n$ is the length of the expression `expression`. + ### **Python3** diff --git a/solution/1100-1199/1108.Defanging an IP Address/README_EN.md b/solution/1100-1199/1108.Defanging an IP Address/README_EN.md index fd084c857a60d..e52608592d259 100644 --- a/solution/1100-1199/1108.Defanging an IP Address/README_EN.md +++ b/solution/1100-1199/1108.Defanging an IP Address/README_EN.md @@ -25,6 +25,12 @@ ## Solutions +**Solution 1: Direct Replacement** + +We can directly replace the `'.'` in the string with `'[.]'`. + +The time complexity is $O(n),ドル where $n$ is the length of the string. Ignoring the space consumption of the answer, the space complexity is $O(1)$. + ### **Python3** 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 2af09b3d13c08..e47380dae28ca 100644 --- a/solution/1100-1199/1109.Corporate Flight Bookings/README_EN.md +++ b/solution/1100-1199/1109.Corporate Flight Bookings/README_EN.md @@ -52,6 +52,27 @@ Hence, answer = [10,25] ## Solutions +**Solution 1: Difference Array** + +We notice that each booking is for `seats` seats on all flights within a certain interval `[first, last]`. Therefore, we can use the idea of a difference array. For each booking, we add `seats` to the number at the `first` position and subtract `seats` from the number at the `last + 1` position. Finally, we calculate the prefix sum of the difference array to get the total number of seats booked for each flight. + +The time complexity is $O(n),ドル where $n$ is the number of flights. Ignoring the space consumption of the answer, the space complexity is $O(1)$. + +**Solution 2: Binary Indexed Tree + Difference Idea** + +We can also use a binary indexed tree, combined with the idea of difference, to implement the above operations. We can consider each booking as booking `seats` seats on all flights within a certain interval `[first, last]`. Therefore, for each booking, we add `seats` to the `first` position of the binary indexed tree and subtract `seats` from the `last + 1` position of the binary indexed tree. Finally, we calculate the prefix sum for each position in the binary indexed tree to get the total number of seats booked for each flight. + +The time complexity is $O(n \times \log n),ドル and the space complexity is $O(n)$. Here, $n$ is the number of flights. + +Here is a basic introduction to the binary indexed tree: + +A binary indexed tree, also known as a "Binary Indexed Tree" or Fenwick tree. It can efficiently implement the following two operations: + +1. **Single Point Update** `update(x, delta)`: Add a value delta to the number at position x in the sequence; +1. **Prefix Sum Query** `query(x)`: Query the interval sum of the sequence `[1,...x]`, that is, the prefix sum of position x. + +The time complexity of these two operations is $O(\log n)$. + ### **Python3** diff --git a/solution/1100-1199/1110.Delete Nodes And Return Forest/README_EN.md b/solution/1100-1199/1110.Delete Nodes And Return Forest/README_EN.md index a7398ebcc4ade..299f7e0cc6428 100644 --- a/solution/1100-1199/1110.Delete Nodes And Return Forest/README_EN.md +++ b/solution/1100-1199/1110.Delete Nodes And Return Forest/README_EN.md @@ -37,6 +37,19 @@ ## Solutions +**Solution 1: DFS** + +First, we use a hash table or an array of length 1001, `s`, to record all nodes that need to be deleted. + +Next, we design a function `dfs(root)` that returns the root of the subtree with `root` as the root after deleting all nodes that need to be deleted. The execution logic of the function `dfs(root)` is as follows: + +- If `root` is null, we return null; +- Otherwise, we recursively execute `dfs(root.left)` and `dfs(root.right)`, and assign the return values to `root.left` and `root.right` respectively. If `root` does not need to be deleted, we return `root`; if `root` needs to be deleted, we check whether `root.left` and `root.right` are null. If they are not null, we add them to the answer array; finally, we return null. + +In the main function, we call `dfs(root)`. If the result is not null, it means that the root node does not need to be deleted, and we add the root node to the answer array. Finally, we return the answer array. + +The time complexity is $O(n),ドル and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the tree. + ### **Python3** diff --git a/solution/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README_EN.md b/solution/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README_EN.md index b3614a85137e7..c8a317e9f5fdf 100644 --- a/solution/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README_EN.md +++ b/solution/1100-1199/1111.Maximum Nesting Depth of Two Valid Parentheses Strings/README_EN.md @@ -54,6 +54,14 @@ ## Solutions +**Solution 1: Greedy** + +We use a variable $x$ to maintain the current balance of parentheses, which is the number of left parentheses minus the number of right parentheses. + +We traverse the string $seq,ドル updating the value of $x$. If $x$ is odd, we assign the current left parenthesis to $A,ドル otherwise we assign it to $B$. + +The time complexity is $O(n),ドル where $n$ is the length of the string $seq$. Ignoring the space consumption of the answer, the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1100-1199/1114.Print in Order/README_EN.md b/solution/1100-1199/1114.Print in Order/README_EN.md index 40b486f3bb9cc..bb228bdac50be 100644 --- a/solution/1100-1199/1114.Print in Order/README_EN.md +++ b/solution/1100-1199/1114.Print in Order/README_EN.md @@ -46,6 +46,18 @@ public class Foo { ## Solutions +**Solution 1: Multithreading + Lock or Semaphore** + +We can use three semaphores $a,ドル $b,ドル and $c$ to control the execution order of the three threads. Initially, the count of semaphore $a$ is 1ドル,ドル and the counts of $b$ and $c$ are 0ドル$. + +When thread $A$ executes the `first()` method, it first needs to acquire semaphore $a$. After acquiring successfully, it executes the `first()` method, and then releases semaphore $b$. This allows thread $B$ to acquire semaphore $b$ and execute the `second()` method. + +When thread $B$ executes the `second()` method, it first needs to acquire semaphore $b$. After acquiring successfully, it executes the `second()` method, and then releases semaphore $c$. This allows thread $C$ to acquire semaphore $c$ and execute the `third()` method. + +When thread $C$ executes the `third()` method, it first needs to acquire semaphore $c$. After acquiring successfully, it executes the `third()` method, and then releases semaphore $a$. This allows thread $A$ to acquire semaphore $a$ and execute the `first()` method. + +The time complexity is $O(1),ドル and the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1100-1199/1115.Print FooBar Alternately/README_EN.md b/solution/1100-1199/1115.Print FooBar Alternately/README_EN.md index 59aa191daff02..24620014b5f47 100644 --- a/solution/1100-1199/1115.Print FooBar Alternately/README_EN.md +++ b/solution/1100-1199/1115.Print FooBar Alternately/README_EN.md @@ -58,6 +58,18 @@ class FooBar { ## Solutions +**Solution 1: Multithreading + Semaphore** + +We use two semaphores $f$ and $b$ to control the execution order of the two threads, where $f$ is initially set to 1ドル$ and $b$ is set to 0ドル,ドル indicating that thread $A$ executes first. + +When thread $A$ executes, it first performs the $acquire$ operation on $f,ドル which changes the value of $f$ to 0ドル$. Thread $A$ then gains the right to use $f$ and can execute the $foo$ function. After that, it performs the $release$ operation on $b,ドル changing the value of $b$ to 1ドル$. This allows thread $B$ to gain the right to use $b$ and execute the $bar$ function. + +When thread $B$ executes, it first performs the $acquire$ operation on $b,ドル which changes the value of $b$ to 0ドル$. Thread $B$ then gains the right to use $b$ and can execute the $bar$ function. After that, it performs the $release$ operation on $f,ドル changing the value of $f$ to 1ドル$. This allows thread $A$ to gain the right to use $f$ and execute the $foo$ function. + +Therefore, we only need to loop $n$ times, each time executing the $foo$ and $bar$ functions, first performing the $acquire$ operation, and then the $release$ operation. + +The time complexity is $O(n),ドル and the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1100-1199/1116.Print Zero Even Odd/README_EN.md b/solution/1100-1199/1116.Print Zero Even Odd/README_EN.md index e45f0def12a12..e47dd4495560e 100644 --- a/solution/1100-1199/1116.Print Zero Even Odd/README_EN.md +++ b/solution/1100-1199/1116.Print Zero Even Odd/README_EN.md @@ -56,6 +56,16 @@ One of them calls zero(), the other calls even(), and the last one calls odd(). ## Solutions +**Solution 1: Multithreading + Semaphore** + +We use three semaphores $z,ドル $e,ドル and $o$ to control the execution order of the three threads, where $z$ is initially set to 1ドル,ドル and $e$ and $o$ are set to 0ドル$. + +- Semaphore $z$ controls the execution of the `zero` function. When the value of semaphore $z$ is 1ドル,ドル the `zero` function can be executed. After execution, the value of semaphore $z$ is set to 0ドル,ドル and the value of semaphore $e$ or $o$ is set to 1ドル,ドル depending on whether the `even` function or the `odd` function needs to be executed next. +- Semaphore $e$ controls the execution of the `even` function. When the value of semaphore $e$ is 1ドル,ドル the `even` function can be executed. After execution, the value of semaphore $z$ is set to 1ドル,ドル and the value of semaphore $e$ is set to 0ドル$. +- Semaphore $o$ controls the execution of the `odd` function. When the value of semaphore $o$ is 1ドル,ドル the `odd` function can be executed. After execution, the value of semaphore $z$ is set to 1ドル,ドル and the value of semaphore $o$ is set to 0ドル$. + +The time complexity is $O(n),ドル and the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1100-1199/1118.Number of Days in a Month/README_EN.md b/solution/1100-1199/1118.Number of Days in a Month/README_EN.md index b99f2dfa9772e..ef7d5982ca0a4 100644 --- a/solution/1100-1199/1118.Number of Days in a Month/README_EN.md +++ b/solution/1100-1199/1118.Number of Days in a Month/README_EN.md @@ -27,6 +27,16 @@ ## Solutions +**Solution 1: Determine Leap Year** + +We can first determine whether the given year is a leap year. If the year can be divided by 4ドル$ but not by 100ドル,ドル or can be divided by 400ドル,ドル then this year is a leap year. + +February has 29ドル$ days in a leap year and 28ドル$ days in a common year. + +We can use an array $days$ to store the number of days in each month of the current year, where $days[0]=0,ドル $days[i]$ represents the number of days in the $i$th month of the current year. Then the answer is $days[month]$. + +The time complexity is $O(1),ドル and the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1100-1199/1119.Remove Vowels from a String/README_EN.md b/solution/1100-1199/1119.Remove Vowels from a String/README_EN.md index a079b1c614a03..01cfb53f1bc79 100644 --- a/solution/1100-1199/1119.Remove Vowels from a String/README_EN.md +++ b/solution/1100-1199/1119.Remove Vowels from a String/README_EN.md @@ -31,6 +31,12 @@ ## Solutions +**Solution 1: Simulation** + +We can directly traverse the string according to the requirements of the problem, and append characters that are not vowels to the result string. + +The time complexity is $O(n),ドル where $n$ is the length of the string. Ignoring the space consumption of the answer, the space complexity is $O(1)$. + ### **Python3** diff --git a/solution/1100-1199/1120.Maximum Average Subtree/README_EN.md b/solution/1100-1199/1120.Maximum Average Subtree/README_EN.md index f819d45319550..34d12c67079ff 100644 --- a/solution/1100-1199/1120.Maximum Average Subtree/README_EN.md +++ b/solution/1100-1199/1120.Maximum Average Subtree/README_EN.md @@ -40,6 +40,22 @@ So the answer is 6 which is the maximum. ## Solutions +**Solution 1: Recursion** + +We can use a recursive method. For each node, we calculate the sum and count of the nodes in the subtree rooted at that node, then calculate the average, compare it with the current maximum, and update the maximum if necessary. + +Therefore, we design a function `dfs(root)` that represents the sum and count of nodes in the subtree rooted at `root`. The return value is an array of length 2, where the first element represents the sum of nodes, and the second element represents the count of nodes. + +The recursive process of the function `dfs(root)` is as follows: + +- If `root` is null, return `[0, 0]`; +- Otherwise, calculate the sum and count of nodes in the left subtree of `root`, denoted as `[ls, ln]`; calculate the sum and count of nodes in the right subtree of `root`, denoted as `[rs, rn]`. The sum of nodes in the subtree rooted at `root` is `root.val + ls + rs`, and the count of nodes is `1 + ln + rn`. Calculate the average, compare it with the current maximum, and update the maximum if necessary; +- Return `[root.val + ls + rs, 1 + ln + rn]`. + +Finally, return the maximum value. + +The time complexity is $O(n),ドル and the space complexity is $O(n)$. Here, $n$ is the number of nodes in the binary tree. + ### **Python3** diff --git a/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README.md b/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README.md index 0424e32fdf876..ec0323ea9efdd 100644 --- a/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README.md +++ b/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README.md @@ -44,7 +44,7 @@ 我们假设可以将数组分成 $m$ 个长度至少为 $k$ 的严格递增子序列,如果数组中出现次数最多的数字的个数为 $cnt,ドル那么这 $cnt$ 个数字必须在不同的子序列中,所以 $m \geq cnt,ドル又因为 $m$ 个子序列的长度至少为 $k,ドル因此,子序列的个数越少越好,所以 $m = cnt$。那么 $cnt \times k \leq n,ドル才能满足题意。因此,我们只需要统计数组中出现次数最多的数字的个数 $cnt,ドル然后判断 $cnt \times k \leq n$ 即可。如果是,返回 `true`,否则返回 `false`。 -时间复杂度 $O(n),ドル空间复杂度 $O(1)$。其中 $n$ 为数组 `nums` 的长度。 +时间复杂度 $O(n),ドル空间复杂度 $O(1)$。其中 $n$ 为数组 $nums$ 的长度。 diff --git a/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README_EN.md b/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README_EN.md index 36ca47d8d0228..f26f732ef5c81 100644 --- a/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README_EN.md +++ b/solution/1100-1199/1121.Divide Array Into Increasing Sequences/README_EN.md @@ -34,6 +34,12 @@ ## Solutions +**Solution 1: Quick Thinking** + +We assume that the array can be divided into $m$ strictly increasing subsequences of length at least $k$. If the number of the most frequent number in the array is $cnt,ドル then these $cnt$ numbers must be in different subsequences, so $m \geq cnt$. Also, since the length of $m$ subsequences is at least $k,ドル the fewer the number of subsequences, the better, so $m = cnt$. Therefore, $cnt \times k \leq n$ must be satisfied. Hence, we only need to count the number of the most frequent number $cnt$ in the array, and then judge whether $cnt \times k \leq n$. If it is, return `true`, otherwise return `false`. + +The time complexity is $O(n),ドル and the space complexity is $O(1)$. Here, $n$ is the length of the array $nums$. + ### **Python3** diff --git a/solution/1100-1199/1122.Relative Sort Array/README_EN.md b/solution/1100-1199/1122.Relative Sort Array/README_EN.md index d5b0c2e45842c..e025a33b6b7ff 100644 --- a/solution/1100-1199/1122.Relative Sort Array/README_EN.md +++ b/solution/1100-1199/1122.Relative Sort Array/README_EN.md @@ -35,6 +35,12 @@ ## Solutions +**Solution 1: Custom Sorting** + +First, we use a hash table $pos$ to record the position of each element in array $arr2$. Then, we map each element in array $arr1$ to a tuple $(pos.get(x, 1000 + x), x),ドル and sort these tuples. Finally, we take out the second element of all tuples and return it. + +The time complexity is $O(n \times \log n + m),ドル and the space complexity is $O(n + m)$. Here, $n$ and $m$ are the lengths of arrays $arr1$ and $arr2,ドル respectively. + ### **Python3** diff --git a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README.md b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README.md index 39cdaade9fb30..61942253a120f 100644 --- a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README.md +++ b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README.md @@ -69,7 +69,21 @@ ```python - +class Solution: + def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]: + n = len(nums) + arr = sorted(zip(nums, range(n))) + ans = [0] * n + i = 0 + while i < n: + j = i + 1 + while j < n and arr[j][0] - arr[j - 1][0] <= limit: + j += 1 + idx = sorted(k for _, k in arr[i:j]) + for k, (x, _) in zip(idx, arr[i:j]): + ans[k] = x + i = j + return ans ``` ### **Java** @@ -77,19 +91,110 @@ ```java - +class Solution { + public int[] lexicographicallySmallestArray(int[] nums, int limit) { + int n = nums.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); + int[] ans = new int[n]; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { + ++j; + } + Integer[] t = Arrays.copyOfRange(idx, i, j); + Arrays.sort(t, (x, y) -> x - y); + for (int k = i; k < j; ++k) { + ans[t[k - i]] = nums[idx[k]]; + } + i = j; + } + return ans; + } +} ``` ### **C++** ```cpp - +class Solution { +public: + vector lexicographicallySmallestArray(vector& nums, int limit) { + int n = nums.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return nums[i] < nums[j]; + }); + vector ans(n); + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { + ++j; + } + vector t(idx.begin() + i, idx.begin() + j); + sort(t.begin(), t.end()); + for (int k = i; k < j; ++k) { + ans[t[k - i]] = nums[idx[k]]; + } + i = j; + } + return ans; + } +}; ``` ### **Go** ```go +func lexicographicallySmallestArray(nums []int, limit int) []int { + n := len(nums) + idx := make([]int, n) + for i := range idx { + idx[i] = i + } + slices.SortFunc(idx, func(i, j int) int { return nums[i] - nums[j] }) + ans := make([]int, n) + for i := 0; i < n; { + j := i + 1 + for j < n && nums[idx[j]]-nums[idx[j-1]] <= limit { + j++ + } + t := slices.Clone(idx[i:j]) + slices.Sort(t) + for k := i; k < j; k++ { + ans[t[k-i]] = nums[idx[k]] + } + i = j + } + return ans +} +``` +### **TypeScript** + +```ts +function lexicographicallySmallestArray(nums: number[], limit: number): number[] { + const n: number = nums.length; + const idx: number[] = Array.from({ length: n }, (_, i) => i); + idx.sort((i, j) => nums[i] - nums[j]); + const ans: number[] = Array(n).fill(0); + for (let i = 0; i < n; ) { + let j = i + 1; + while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { + j++; + } + const t: number[] = idx.slice(i, j).sort((a, b) => a - b); + for (let k: number = i; k < j; k++) { + ans[t[k - i]] = nums[idx[k]]; + } + i = j; + } + return ans; +} ``` ### **...** diff --git a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README_EN.md b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README_EN.md index 91a0bbe36173f..f1c079832d3b2 100644 --- a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README_EN.md +++ b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/README_EN.md @@ -61,25 +61,130 @@ We cannot obtain a lexicographically smaller array by applying any more operatio ### **Python3** ```python - +class Solution: + def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]: + n = len(nums) + arr = sorted(zip(nums, range(n))) + ans = [0] * n + i = 0 + while i < n: + j = i + 1 + while j < n and arr[j][0] - arr[j - 1][0] <= limit: + j += 1 + idx = sorted(k for _, k in arr[i:j]) + for k, (x, _) in zip(idx, arr[i:j]): + ans[k] = x + i = j + return ans ``` ### **Java** ```java - +class Solution { + public int[] lexicographicallySmallestArray(int[] nums, int limit) { + int n = nums.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); + int[] ans = new int[n]; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { + ++j; + } + Integer[] t = Arrays.copyOfRange(idx, i, j); + Arrays.sort(t, (x, y) -> x - y); + for (int k = i; k < j; ++k) { + ans[t[k - i]] = nums[idx[k]]; + } + i = j; + } + return ans; + } +} ``` ### **C++** ```cpp - +class Solution { +public: + vector lexicographicallySmallestArray(vector& nums, int limit) { + int n = nums.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return nums[i] < nums[j]; + }); + vector ans(n); + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { + ++j; + } + vector t(idx.begin() + i, idx.begin() + j); + sort(t.begin(), t.end()); + for (int k = i; k < j; ++k) { + ans[t[k - i]] = nums[idx[k]]; + } + i = j; + } + return ans; + } +}; ``` ### **Go** ```go +func lexicographicallySmallestArray(nums []int, limit int) []int { + n := len(nums) + idx := make([]int, n) + for i := range idx { + idx[i] = i + } + slices.SortFunc(idx, func(i, j int) int { return nums[i] - nums[j] }) + ans := make([]int, n) + for i := 0; i < n; { + j := i + 1 + for j < n && nums[idx[j]]-nums[idx[j-1]] <= limit { + j++ + } + t := slices.Clone(idx[i:j]) + slices.Sort(t) + for k := i; k < j; k++ { + ans[t[k-i]] = nums[idx[k]] + } + i = j + } + return ans +} +``` +### **TypeScript** + +```ts +function lexicographicallySmallestArray(nums: number[], limit: number): number[] { + const n: number = nums.length; + const idx: number[] = Array.from({ length: n }, (_, i) => i); + idx.sort((i, j) => nums[i] - nums[j]); + const ans: number[] = Array(n).fill(0); + for (let i = 0; i < n; ) { + let j = i + 1; + while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { + j++; + } + const t: number[] = idx.slice(i, j).sort((a, b) => a - b); + for (let k: number = i; k < j; k++) { + ans[t[k - i]] = nums[idx[k]]; + } + i = j; + } + return ans; +} ``` ### **...** diff --git a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.cpp b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.cpp new file mode 100644 index 0000000000000..7e7ec5fd661fd --- /dev/null +++ b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.cpp @@ -0,0 +1,25 @@ +class Solution { +public: + vector lexicographicallySmallestArray(vector& nums, int limit) { + int n = nums.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + return nums[i] < nums[j]; + }); + vector ans(n); + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { + ++j; + } + vector t(idx.begin() + i, idx.begin() + j); + sort(t.begin(), t.end()); + for (int k = i; k < j; ++k) { + ans[t[k - i]] = nums[idx[k]]; + } + i = j; + } + return ans; + } +}; \ No newline at end of file diff --git a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.go b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.go new file mode 100644 index 0000000000000..ec2d4074d5f81 --- /dev/null +++ b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.go @@ -0,0 +1,22 @@ +func lexicographicallySmallestArray(nums []int, limit int) []int { + n := len(nums) + idx := make([]int, n) + for i := range idx { + idx[i] = i + } + slices.SortFunc(idx, func(i, j int) int { return nums[i] - nums[j] }) + ans := make([]int, n) + for i := 0; i < n; { + j := i + 1 + for j < n && nums[idx[j]]-nums[idx[j-1]] <= limit { + j++ + } + t := slices.Clone(idx[i:j]) + slices.Sort(t) + for k := i; k < j; k++ { + ans[t[k-i]] = nums[idx[k]] + } + i = j + } + return ans +} \ No newline at end of file diff --git a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.java b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.java new file mode 100644 index 0000000000000..632b45ece4031 --- /dev/null +++ b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.java @@ -0,0 +1,24 @@ +class Solution { + public int[] lexicographicallySmallestArray(int[] nums, int limit) { + int n = nums.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; ++i) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> nums[i] - nums[j]); + int[] ans = new int[n]; + for (int i = 0; i < n;) { + int j = i + 1; + while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { + ++j; + } + Integer[] t = Arrays.copyOfRange(idx, i, j); + Arrays.sort(t, (x, y) -> x - y); + for (int k = i; k < j; ++k) { + ans[t[k - i]] = nums[idx[k]]; + } + i = j; + } + return ans; + } +} \ No newline at end of file diff --git a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.py b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.py new file mode 100644 index 0000000000000..d7ea61bd24f4a --- /dev/null +++ b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.py @@ -0,0 +1,15 @@ +class Solution: + def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]: + n = len(nums) + arr = sorted(zip(nums, range(n))) + ans = [0] * n + i = 0 + while i < n: + j = i + 1 + while j < n and arr[j][0] - arr[j - 1][0] <= limit: + j += 1 + idx = sorted(k for _, k in arr[i:j]) + for k, (x, _) in zip(idx, arr[i:j]): + ans[k] = x + i = j + return ans diff --git a/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.ts b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.ts new file mode 100644 index 0000000000000..24d67e9de68c6 --- /dev/null +++ b/solution/2900-2999/2948.Make Lexicographically Smallest Array by Swapping Elements/Solution.ts @@ -0,0 +1,18 @@ +function lexicographicallySmallestArray(nums: number[], limit: number): number[] { + const n: number = nums.length; + const idx: number[] = Array.from({ length: n }, (_, i) => i); + idx.sort((i, j) => nums[i] - nums[j]); + const ans: number[] = Array(n).fill(0); + for (let i = 0; i < n; ) { + let j = i + 1; + while (j < n && nums[idx[j]] - nums[idx[j - 1]] <= limit) { + j++; + } + const t: number[] = idx.slice(i, j).sort((a, b) => a - b); + for (let k: number = i; k < j; k++) { + ans[t[k - i]] = nums[idx[k]]; + } + i = j; + } + return ans; +}

AltStyle によって変換されたページ (->オリジナル) /