diff --git a/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README.md b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README.md new file mode 100644 index 0000000000000..065618e92e034 --- /dev/null +++ b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README.md @@ -0,0 +1,109 @@ +# [2819. Minimum Relative Loss After Buying Chocolates](https://leetcode.cn/problems/minimum-relative-loss-after-buying-chocolates) + +[English Version](/solution/2800-2899/2819.Minimum%20Relative%20Loss%20After%20Buying%20Chocolates/README_EN.md) + +## 题目描述 + + + +

You are given an integer array prices, which shows the chocolate prices and a 2D integer array queries, where queries[i] = [ki, mi].

+ +

Alice and Bob went to buy some chocolates, and Alice suggested a way to pay for them, and Bob agreed.

+ +

The terms for each query are as follows:

+ + + +

Bob wants to select exactly mi chocolates such that his relative loss is minimized, more formally, if, in total, Alice has paid ai and Bob has paid bi, Bob wants to minimize bi - ai.

+ +

Return an integer array ans where ans[i] is Bob's minimum relative loss possible for queries[i].

+ +

 

+

Example 1:

+ +
+Input: prices = [1,9,22,10,19], queries = [[18,4],[5,2]]
+Output: [34,-21]
+Explanation: For the 1st query Bob selects the chocolates with prices [1,9,10,22]. He pays 1 + 9 + 10 + 18 = 38 and Alice pays 0 + 0 + 0 + 4 = 4. So Bob's relative loss is 38 - 4 = 34.
+For the 2nd query Bob selects the chocolates with prices [19,22]. He pays 5 + 5 = 10 and Alice pays 14 + 17 = 31. So Bob's relative loss is 10 - 31 = -21.
+It can be shown that these are the minimum possible relative losses.
+ +

Example 2:

+ +
+Input: prices = [1,5,4,3,7,11,9], queries = [[5,4],[5,7],[7,3],[4,5]]
+Output: [4,16,7,1]
+Explanation: For the 1st query Bob selects the chocolates with prices [1,3,9,11]. He pays 1 + 3 + 5 + 5 = 14 and Alice pays 0 + 0 + 4 + 6 = 10. So Bob's relative loss is 14 - 10 = 4.
+For the 2nd query Bob has to select all the chocolates. He pays 1 + 5 + 4 + 3 + 5 + 5 + 5 = 28 and Alice pays 0 + 0 + 0 + 0 + 2 + 6 + 4 = 12. So Bob's relative loss is 28 - 12 = 16.
+For the 3rd query Bob selects the chocolates with prices [1,3,11] and he pays 1 + 3 + 7 = 11 and Alice pays 0 + 0 + 4 = 4. So Bob's relative loss is 11 - 4 = 7.
+For the 4th query Bob selects the chocolates with prices [1,3,7,9,11] and he pays 1 + 3 + 4 + 4 + 4 = 16 and Alice pays 0 + 0 + 3 + 5 + 7 = 15. So Bob's relative loss is 16 - 15 = 1.
+It can be shown that these are the minimum possible relative losses.
+
+ +

Example 3:

+ +
+Input: prices = [5,6,7], queries = [[10,1],[5,3],[3,3]]
+Output: [5,12,0]
+Explanation: For the 1st query Bob selects the chocolate with price 5 and he pays 5 and Alice pays 0. So Bob's relative loss is 5 - 0 = 5.
+For the 2nd query Bob has to select all the chocolates. He pays 5 + 5 + 5 = 15 and Alice pays 0 + 1 + 2 = 3. So Bob's relative loss is 15 - 3 = 12.
+For the 3rd query Bob has to select all the chocolates. He pays 3 + 3 + 3 = 9 and Alice pays 2 + 3 + 4 = 9. So Bob's relative loss is 9 - 9 = 0.
+It can be shown that these are the minimum possible relative losses.
+
+ +

 

+

Constraints:

+ + + +## 解法 + + + + + +### **Python3** + + + +```python + +``` + +### **Java** + + + +```java + +``` + +### **C++** + +```cpp + +``` + +### **Go** + +```go + +``` + +### **...** + +``` + +``` + + diff --git a/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README_EN.md b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README_EN.md new file mode 100644 index 0000000000000..7fa53213dd5bb --- /dev/null +++ b/solution/2800-2899/2819.Minimum Relative Loss After Buying Chocolates/README_EN.md @@ -0,0 +1,101 @@ +# [2819. Minimum Relative Loss After Buying Chocolates](https://leetcode.com/problems/minimum-relative-loss-after-buying-chocolates) + +[中文文档](/solution/2800-2899/2819.Minimum%20Relative%20Loss%20After%20Buying%20Chocolates/README.md) + +## Description + +

You are given an integer array prices, which shows the chocolate prices and a 2D integer array queries, where queries[i] = [ki, mi].

+ +

Alice and Bob went to buy some chocolates, and Alice suggested a way to pay for them, and Bob agreed.

+ +

The terms for each query are as follows:

+ + + +

Bob wants to select exactly mi chocolates such that his relative loss is minimized, more formally, if, in total, Alice has paid ai and Bob has paid bi, Bob wants to minimize bi - ai.

+ +

Return an integer array ans where ans[i] is Bob's minimum relative loss possible for queries[i].

+ +

 

+

Example 1:

+ +
+Input: prices = [1,9,22,10,19], queries = [[18,4],[5,2]]
+Output: [34,-21]
+Explanation: For the 1st query Bob selects the chocolates with prices [1,9,10,22]. He pays 1 + 9 + 10 + 18 = 38 and Alice pays 0 + 0 + 0 + 4 = 4. So Bob's relative loss is 38 - 4 = 34.
+For the 2nd query Bob selects the chocolates with prices [19,22]. He pays 5 + 5 = 10 and Alice pays 14 + 17 = 31. So Bob's relative loss is 10 - 31 = -21.
+It can be shown that these are the minimum possible relative losses.
+ +

Example 2:

+ +
+Input: prices = [1,5,4,3,7,11,9], queries = [[5,4],[5,7],[7,3],[4,5]]
+Output: [4,16,7,1]
+Explanation: For the 1st query Bob selects the chocolates with prices [1,3,9,11]. He pays 1 + 3 + 5 + 5 = 14 and Alice pays 0 + 0 + 4 + 6 = 10. So Bob's relative loss is 14 - 10 = 4.
+For the 2nd query Bob has to select all the chocolates. He pays 1 + 5 + 4 + 3 + 5 + 5 + 5 = 28 and Alice pays 0 + 0 + 0 + 0 + 2 + 6 + 4 = 12. So Bob's relative loss is 28 - 12 = 16.
+For the 3rd query Bob selects the chocolates with prices [1,3,11] and he pays 1 + 3 + 7 = 11 and Alice pays 0 + 0 + 4 = 4. So Bob's relative loss is 11 - 4 = 7.
+For the 4th query Bob selects the chocolates with prices [1,3,7,9,11] and he pays 1 + 3 + 4 + 4 + 4 = 16 and Alice pays 0 + 0 + 3 + 5 + 7 = 15. So Bob's relative loss is 16 - 15 = 1.
+It can be shown that these are the minimum possible relative losses.
+
+ +

Example 3:

+ +
+Input: prices = [5,6,7], queries = [[10,1],[5,3],[3,3]]
+Output: [5,12,0]
+Explanation: For the 1st query Bob selects the chocolate with price 5 and he pays 5 and Alice pays 0. So Bob's relative loss is 5 - 0 = 5.
+For the 2nd query Bob has to select all the chocolates. He pays 5 + 5 + 5 = 15 and Alice pays 0 + 1 + 2 = 3. So Bob's relative loss is 15 - 3 = 12.
+For the 3rd query Bob has to select all the chocolates. He pays 3 + 3 + 3 = 9 and Alice pays 2 + 3 + 4 = 9. So Bob's relative loss is 9 - 9 = 0.
+It can be shown that these are the minimum possible relative losses.
+
+ +

 

+

Constraints:

+ + + +## Solutions + + + +### **Python3** + +```python + +``` + +### **Java** + +```java + +``` + +### **C++** + +```cpp + +``` + +### **Go** + +```go + +``` + +### **...** + +``` + +``` + + diff --git a/solution/2800-2899/2820.Election Results/README.md b/solution/2800-2899/2820.Election Results/README.md new file mode 100644 index 0000000000000..9022b5abeaa31 --- /dev/null +++ b/solution/2800-2899/2820.Election Results/README.md @@ -0,0 +1,105 @@ +# [2820. Election Results](https://leetcode.cn/problems/election-results) + +[English Version](/solution/2800-2899/2820.Election%20Results/README_EN.md) + +## 题目描述 + + + +

Table: Votes

+ +
++-------------+---------+ 
+| Column Name | Type    | 
++-------------+---------+ 
+| voter       | varchar | 
+| candidate   | varchar |
++-------------+---------+
+(voter, candidate) is the primary key for this table.
+Each row of this table contains name of the voter and their candidate. 
+
+ +

The election is conducted in a city where everyone can vote for one or more candidates or choose not to vote. Each person has 1 vote so if they vote for multiple candidates, their vote gets equally split across them. For example, if a person votes for 2 candidates, these candidates receive an equivalent of 0.5 votes each.

+ +

Write an SQL query to find candidate who got the most votes and won the election. Output the name of the candidate or If multiple candidates have an equal number of votes, display the names of all of them.

+ +

Return the result table ordered by candidate in ascending order.

+ +

The query result format is in the following example.

+ +

 

+

Example 1:

+ +
+Input: 
+Votes table:
++----------+-----------+
+| voter    | candidate |
++----------+-----------+
+| Kathy    | null      |
+| Charles  | Ryan      |
+| Charles  | Christine |
+| Charles  | Kathy     |
+| Benjamin | Christine |
+| Anthony  | Ryan      |
+| Edward   | Ryan      |
+| Terry    | null      |
+| Evelyn   | Kathy     |
+| Arthur   | Christine |
++----------+-----------+
+Output: 
++-----------+
+| candidate | 
++-----------+
+| Christine |  
+| Ryan      |  
++-----------+
+Explanation: 
+- Kathy and Terry opted not to participate in voting, resulting in their votes being recorded as 0. Charles distributed his vote among three candidates, equating to 0.33 for each candidate. On the other hand, Benjamin, Arthur, Anthony, Edward, and Evelyn each cast their votes for a single candidate.
+- Collectively, Candidate Ryan and Christine amassed a total of 2.33 votes, while Kathy received a combined total of 1.33 votes.
+Since Ryan and Christine received an equal number of votes, we will display their names in ascending order.
+ +## 解法 + + + +**方法一:窗口函数 + 分组统计** + +我们可以使用窗口函数 `count` 计算每个投票人投给的候选人的票数,然后再使用分组统计函数 `sum` 计算每个候选人的总票数,最后使用窗口函数 `rank` 计算每个候选人的排名,最后筛选出排名第一的候选人即可。 + +注意,结果集中可能会有多个排名第一的候选人,因此我们需要使用 `order by` 对候选人进行排序。 + + + +### **SQL** + + + +```sql +# Write your MySQL query statement below +WITH + T AS ( + SELECT candidate, sum(vote) AS tot + FROM + ( + SELECT + candidate, + 1 / (count(candidate) OVER (PARTITION BY voter)) AS vote + FROM Votes + WHERE candidate IS NOT NULL + ) AS t + GROUP BY 1 + ), + P AS ( + SELECT + candidate, + rank() OVER (ORDER BY tot DESC) AS rk + FROM T + ) +SELECT candidate +FROM P +WHERE rk = 1 +ORDER BY 1; +``` + + diff --git a/solution/2800-2899/2820.Election Results/README_EN.md b/solution/2800-2899/2820.Election Results/README_EN.md new file mode 100644 index 0000000000000..1c43e496cece8 --- /dev/null +++ b/solution/2800-2899/2820.Election Results/README_EN.md @@ -0,0 +1,93 @@ +# [2820. Election Results](https://leetcode.com/problems/election-results) + +[中文文档](/solution/2800-2899/2820.Election%20Results/README.md) + +## Description + +

Table: Votes

+ +
++-------------+---------+ 
+| Column Name | Type    | 
++-------------+---------+ 
+| voter       | varchar | 
+| candidate   | varchar |
++-------------+---------+
+(voter, candidate) is the primary key for this table.
+Each row of this table contains name of the voter and their candidate. 
+
+ +

The election is conducted in a city where everyone can vote for one or more candidates or choose not to vote. Each person has 1 vote so if they vote for multiple candidates, their vote gets equally split across them. For example, if a person votes for 2 candidates, these candidates receive an equivalent of 0.5 votes each.

+ +

Write an SQL query to find candidate who got the most votes and won the election. Output the name of the candidate or If multiple candidates have an equal number of votes, display the names of all of them.

+ +

Return the result table ordered by candidate in ascending order.

+ +

The query result format is in the following example.

+ +

 

+

Example 1:

+ +
+Input: 
+Votes table:
++----------+-----------+
+| voter    | candidate |
++----------+-----------+
+| Kathy    | null      |
+| Charles  | Ryan      |
+| Charles  | Christine |
+| Charles  | Kathy     |
+| Benjamin | Christine |
+| Anthony  | Ryan      |
+| Edward   | Ryan      |
+| Terry    | null      |
+| Evelyn   | Kathy     |
+| Arthur   | Christine |
++----------+-----------+
+Output: 
++-----------+
+| candidate | 
++-----------+
+| Christine |  
+| Ryan      |  
++-----------+
+Explanation: 
+- Kathy and Terry opted not to participate in voting, resulting in their votes being recorded as 0. Charles distributed his vote among three candidates, equating to 0.33 for each candidate. On the other hand, Benjamin, Arthur, Anthony, Edward, and Evelyn each cast their votes for a single candidate.
+- Collectively, Candidate Ryan and Christine amassed a total of 2.33 votes, while Kathy received a combined total of 1.33 votes.
+Since Ryan and Christine received an equal number of votes, we will display their names in ascending order.
+ +## Solutions + + + +### **SQL** + +```sql +# Write your MySQL query statement below +WITH + T AS ( + SELECT candidate, sum(vote) AS tot + FROM + ( + SELECT + candidate, + 1 / (count(candidate) OVER (PARTITION BY voter)) AS vote + FROM Votes + WHERE candidate IS NOT NULL + ) AS t + GROUP BY 1 + ), + P AS ( + SELECT + candidate, + rank() OVER (ORDER BY tot DESC) AS rk + FROM T + ) +SELECT candidate +FROM P +WHERE rk = 1 +ORDER BY 1; +``` + + diff --git a/solution/2800-2899/2820.Election Results/Solution.sql b/solution/2800-2899/2820.Election Results/Solution.sql new file mode 100644 index 0000000000000..94472ef7e693c --- /dev/null +++ b/solution/2800-2899/2820.Election Results/Solution.sql @@ -0,0 +1,24 @@ +# Write your MySQL query statement below +WITH + T AS ( + SELECT candidate, sum(vote) AS tot + FROM + ( + SELECT + candidate, + 1 / (count(candidate) OVER (PARTITION BY voter)) AS vote + FROM Votes + WHERE candidate IS NOT NULL + ) AS t + GROUP BY 1 + ), + P AS ( + SELECT + candidate, + rank() OVER (ORDER BY tot DESC) AS rk + FROM T + ) +SELECT candidate +FROM P +WHERE rk = 1 +ORDER BY 1; diff --git a/solution/2800-2899/2821.Delay the Resolution of Each Promise/README.md b/solution/2800-2899/2821.Delay the Resolution of Each Promise/README.md new file mode 100644 index 0000000000000..3a954348d6c68 --- /dev/null +++ b/solution/2800-2899/2821.Delay the Resolution of Each Promise/README.md @@ -0,0 +1,74 @@ +# [2821. Delay the Resolution of Each Promise](https://leetcode.cn/problems/delay-the-resolution-of-each-promise) + +[English Version](/solution/2800-2899/2821.Delay%20the%20Resolution%20of%20Each%20Promise/README_EN.md) + +## 题目描述 + + + +

Given an array functions and a number ms, return a new array of functions.

+ + + +

Each function in the new array should return a promise that resolves after a delay of ms milliseconds, preserving the order of the original functions array. The delayAll function should ensure that each promise from functions is executed with a delay, forming the new array of functions returning delayed promises.

+ +

 

+

Example 1:

+ +
+Input: 
+functions = [
+   () => new Promise((resolve) => setTimeout(resolve, 30))
+], 
+ms = 50
+Output: [80]
+Explanation: The promise from the array would have resolved after 30 ms, but it was delayed by 50 ms, thus 30 ms + 50 ms = 80 ms.
+
+ +

Example 2:

+ +
+Input: 
+functions = [
+    () => new Promise((resolve) => setTimeout(resolve, 50)),
+    () => new Promise((resolve) => setTimeout(resolve, 80))
+], 
+ms = 70
+Output: [120,150]
+Explanation: The promises from the array would have resolved after 50 ms and 80 ms, but they were delayed by 70 ms, thus 50 ms + 70 ms = 120 ms and 80 ms + 70 ms = 150 ms.
+
+ +

 

+

Constraints:

+ + + +## 解法 + + + + + +### **TypeScript** + + + +```ts +function delayAll(functions: Function[], ms: number): Function[] { + return functions.map(fn => { + return async function () { + await new Promise(resolve => setTimeout(resolve, ms)); + return fn(); + }; + }); +} +``` + + diff --git a/solution/2800-2899/2821.Delay the Resolution of Each Promise/README_EN.md b/solution/2800-2899/2821.Delay the Resolution of Each Promise/README_EN.md new file mode 100644 index 0000000000000..6feafa34db150 --- /dev/null +++ b/solution/2800-2899/2821.Delay the Resolution of Each Promise/README_EN.md @@ -0,0 +1,68 @@ +# [2821. Delay the Resolution of Each Promise](https://leetcode.com/problems/delay-the-resolution-of-each-promise) + +[中文文档](/solution/2800-2899/2821.Delay%20the%20Resolution%20of%20Each%20Promise/README.md) + +## Description + +

Given an array functions and a number ms, return a new array of functions.

+ + + +

Each function in the new array should return a promise that resolves after a delay of ms milliseconds, preserving the order of the original functions array. The delayAll function should ensure that each promise from functions is executed with a delay, forming the new array of functions returning delayed promises.

+ +

 

+

Example 1:

+ +
+Input: 
+functions = [
+   () => new Promise((resolve) => setTimeout(resolve, 30))
+], 
+ms = 50
+Output: [80]
+Explanation: The promise from the array would have resolved after 30 ms, but it was delayed by 50 ms, thus 30 ms + 50 ms = 80 ms.
+
+ +

Example 2:

+ +
+Input: 
+functions = [
+    () => new Promise((resolve) => setTimeout(resolve, 50)),
+    () => new Promise((resolve) => setTimeout(resolve, 80))
+], 
+ms = 70
+Output: [120,150]
+Explanation: The promises from the array would have resolved after 50 ms and 80 ms, but they were delayed by 70 ms, thus 50 ms + 70 ms = 120 ms and 80 ms + 70 ms = 150 ms.
+
+ +

 

+

Constraints:

+ + + +## Solutions + + + +### **TypeScript** + +```ts +function delayAll(functions: Function[], ms: number): Function[] { + return functions.map(fn => { + return async function () { + await new Promise(resolve => setTimeout(resolve, ms)); + return fn(); + }; + }); +} +``` + + diff --git a/solution/2800-2899/2821.Delay the Resolution of Each Promise/Solution.ts b/solution/2800-2899/2821.Delay the Resolution of Each Promise/Solution.ts new file mode 100644 index 0000000000000..26de2c346dea5 --- /dev/null +++ b/solution/2800-2899/2821.Delay the Resolution of Each Promise/Solution.ts @@ -0,0 +1,8 @@ +function delayAll(functions: Function[], ms: number): Function[] { + return functions.map(fn => { + return async function () { + await new Promise(resolve => setTimeout(resolve, ms)); + return fn(); + }; + }); +} diff --git a/solution/2800-2899/2822.Inversion of Object/README.md b/solution/2800-2899/2822.Inversion of Object/README.md new file mode 100644 index 0000000000000..5ddfd75888b4e --- /dev/null +++ b/solution/2800-2899/2822.Inversion of Object/README.md @@ -0,0 +1,74 @@ +# [2822. Inversion of Object](https://leetcode.cn/problems/inversion-of-object) + +[English Version](/solution/2800-2899/2822.Inversion%20of%20Object/README_EN.md) + +## 题目描述 + + + +

Given an object obj, return an inverted object invertedObj.

+ +

The invertedObj should have the keys of obj as values and the values of obj as keys. It is guaranteed that the values in obj are only strings. The function should handle duplicates, meaning that if there are multiple keys in obj with the same value, the invertedObj should map the value to an array containing all corresponding keys.

+ +

 

+

Example 1:

+ +
+Input: obj = {"a": "1", "b": "2", "c": "3", "d": "4"}
+Output: invertedObj = {"1": "a", "2": "b", "3": "c", "4": "d"}
+Explanation: The keys from obj become the values in invertedObj, and the values from obj become the keys in invertedObj.
+
+ +

Example 2:

+ +
+Input: obj = {"a": "1", "b": "2", "c": "2", "d": "4"}
+Output: invertedObj = {"1": "a", "2": ["b", "c"], "4": "d"}
+Explanation: There are two keys in obj with the same value, the invertedObj mapped the value to an array containing all corresponding keys.
+ +

Example 3:

+ +
+Input: obj = ["1", "2", "3", "4"]
+Output: invertedObj = {"1": "0", "2": "1", "3": "2", "4": "3"}
+Explanation: Arrays are also objects therefore array has changed to an object and the keys (indices) from obj become the values in invertedObj, and the values from obj become the keys in invertedObj.
+
+ +

 

+

Constraints:

+ + + +## 解法 + + + + + +### **TypeScript** + + + +```ts +function invertObject(obj: Record): Record { + const ans: Record = {}; + for (const key in obj) { + if (ans.hasOwnProperty(obj[key])) { + if (Array.isArray(ans[obj[key]])) { + ans[obj[key]].push(key); + } else { + ans[obj[key]] = [ans[obj[key]], key]; + } + } else { + ans[obj[key]] = key; + } + } + return ans; +} +``` + + diff --git a/solution/2800-2899/2822.Inversion of Object/README_EN.md b/solution/2800-2899/2822.Inversion of Object/README_EN.md new file mode 100644 index 0000000000000..f1ab38348ecfb --- /dev/null +++ b/solution/2800-2899/2822.Inversion of Object/README_EN.md @@ -0,0 +1,68 @@ +# [2822. Inversion of Object](https://leetcode.com/problems/inversion-of-object) + +[中文文档](/solution/2800-2899/2822.Inversion%20of%20Object/README.md) + +## Description + +

Given an object obj, return an inverted object invertedObj.

+ +

The invertedObj should have the keys of obj as values and the values of obj as keys. It is guaranteed that the values in obj are only strings. The function should handle duplicates, meaning that if there are multiple keys in obj with the same value, the invertedObj should map the value to an array containing all corresponding keys.

+ +

 

+

Example 1:

+ +
+Input: obj = {"a": "1", "b": "2", "c": "3", "d": "4"}
+Output: invertedObj = {"1": "a", "2": "b", "3": "c", "4": "d"}
+Explanation: The keys from obj become the values in invertedObj, and the values from obj become the keys in invertedObj.
+
+ +

Example 2:

+ +
+Input: obj = {"a": "1", "b": "2", "c": "2", "d": "4"}
+Output: invertedObj = {"1": "a", "2": ["b", "c"], "4": "d"}
+Explanation: There are two keys in obj with the same value, the invertedObj mapped the value to an array containing all corresponding keys.
+ +

Example 3:

+ +
+Input: obj = ["1", "2", "3", "4"]
+Output: invertedObj = {"1": "0", "2": "1", "3": "2", "4": "3"}
+Explanation: Arrays are also objects therefore array has changed to an object and the keys (indices) from obj become the values in invertedObj, and the values from obj become the keys in invertedObj.
+
+ +

 

+

Constraints:

+ +
    +
  • obj is a valid JSON object
  • +
  • typeof obj[key] === "string"
  • +
  • 2 <= JSON.stringify(obj).length <= 10**5
  • +
+ +## Solutions + + + +### **TypeScript** + +```ts +function invertObject(obj: Record): Record { + const ans: Record = {}; + for (const key in obj) { + if (ans.hasOwnProperty(obj[key])) { + if (Array.isArray(ans[obj[key]])) { + ans[obj[key]].push(key); + } else { + ans[obj[key]] = [ans[obj[key]], key]; + } + } else { + ans[obj[key]] = key; + } + } + return ans; +} +``` + + diff --git a/solution/2800-2899/2822.Inversion of Object/Solution.ts b/solution/2800-2899/2822.Inversion of Object/Solution.ts new file mode 100644 index 0000000000000..b42ed309f70b3 --- /dev/null +++ b/solution/2800-2899/2822.Inversion of Object/Solution.ts @@ -0,0 +1,15 @@ +function invertObject(obj: Record): Record { + const ans: Record = {}; + for (const key in obj) { + if (ans.hasOwnProperty(obj[key])) { + if (Array.isArray(ans[obj[key]])) { + ans[obj[key]].push(key); + } else { + ans[obj[key]] = [ans[obj[key]], key]; + } + } else { + ans[obj[key]] = key; + } + } + return ans; +} diff --git a/solution/2800-2899/2823.Deep Object Filter/README.md b/solution/2800-2899/2823.Deep Object Filter/README.md new file mode 100644 index 0000000000000..3c81aeb2cf87f --- /dev/null +++ b/solution/2800-2899/2823.Deep Object Filter/README.md @@ -0,0 +1,112 @@ +# [2823. Deep Object Filter](https://leetcode.cn/problems/deep-object-filter) + +[English Version](/solution/2800-2899/2823.Deep%20Object%20Filter/README_EN.md) + +## 题目描述 + + + +

Given an object obj and a function fn, return a filtered object filteredObject

+ +

Function deepFilter should perform a deep filter operation on the object obj. The deep filter operation should remove properties for which the output of the filter function fn is false, as well as any empty objects or arrays that remain after the keys have been removed.

+ +

If the deep filter operation results in an empty object or array, with no remaining properties, deepFilter should return undefined to indicate that there is no valid data left in the filteredObject.

+ +

 

+

Example 1:

+ +
+Input: 
+obj = [-5, -4, -3, -2, -1, 0, 1], 
+fn = (x) => x > 0
+Output: [1]
+Explanation: All values that were not greater than 0 were removed.
+
+ +

Example 2:

+ +
+Input: 
+obj = {"a": 1, "b": "2", "c": 3, "d": "4", "e": 5, "f": 6, "g": {"a": 1}}, 
+fn = (x) => typeof x === "string"
+Output: {"b":"2","d":"4"}
+Explanation: All keys with values that were not a string were removed. When the object keys were removed during the filtering process, any resulting empty objects were also removed.
+
+ +

Example 3:

+ +
+Input: 
+obj = [-1, [-1, -1, 5, -1, 10], -1, [-1], [-5]], 
+fn = (x) => x > 0
+Output: [[5,10]]
+Explanation: All values that were not greater than 0 were removed. When the values were removed during the filtering process, any resulting empty arrays were also removed.
+ +

Example 4:

+ +
+Input: 
+obj = [[[[5]]]], 
+fn = (x) => Array.isArray(x)
+Output: undefined
+
+ +

 

+

Constraints:

+ +
    +
  • fn is a function that returns a boolean value
  • +
  • obj is a valid JSON object
  • +
  • 2 <= JSON.stringify(obj).length <= 10**5
  • +
+ +## 解法 + + + +**方法一:递归** + +我们先判断当前对象是否为数组,如果是数组,我们就对数组中的每一个元素进行递归调用,然后过滤掉返回值为 `undefined` 的元素,最后返回过滤后的数组。 + +如果当前对象不是数组,我们就判断当前对象是否为对象,如果是对象,我们就对对象中的每一个属性值进行递归调用,然后过滤掉返回值为 `undefined` 的属性值,最后返回过滤后的对象。 + +如果当前对象既不是数组也不是对象,我们就直接返回 `fn(obj) ? obj : undefined`。 + +时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为对象中的元素个数。 + + + +### **TypeScript** + + + +```ts +function deepFilter( + obj: Record, + fn: Function, +): Record | undefined { + const dfs = (data: any): any => { + if (Array.isArray(data)) { + const res = data.map(dfs).filter((item: any) => item !== undefined); + return res.length > 0 ? res : undefined; + } + if (typeof data === 'object' && data !== null) { + const res: Record = {}; + for (const key in data) { + if (data.hasOwnProperty(key)) { + const filteredValue = dfs(data[key]); + if (filteredValue !== undefined) { + res[key] = filteredValue; + } + } + } + return Object.keys(res).length > 0 ? res : undefined; + } + return fn(data) ? data : undefined; + }; + + return dfs(obj); +} +``` + + diff --git a/solution/2800-2899/2823.Deep Object Filter/README_EN.md b/solution/2800-2899/2823.Deep Object Filter/README_EN.md new file mode 100644 index 0000000000000..97c7c507a591f --- /dev/null +++ b/solution/2800-2899/2823.Deep Object Filter/README_EN.md @@ -0,0 +1,96 @@ +# [2823. Deep Object Filter](https://leetcode.com/problems/deep-object-filter) + +[中文文档](/solution/2800-2899/2823.Deep%20Object%20Filter/README.md) + +## Description + +

Given an object obj and a function fn, return a filtered object filteredObject

+ +

Function deepFilter should perform a deep filter operation on the object obj. The deep filter operation should remove properties for which the output of the filter function fn is false, as well as any empty objects or arrays that remain after the keys have been removed.

+ +

If the deep filter operation results in an empty object or array, with no remaining properties, deepFilter should return undefined to indicate that there is no valid data left in the filteredObject.

+ +

 

+

Example 1:

+ +
+Input: 
+obj = [-5, -4, -3, -2, -1, 0, 1], 
+fn = (x) => x > 0
+Output: [1]
+Explanation: All values that were not greater than 0 were removed.
+
+ +

Example 2:

+ +
+Input: 
+obj = {"a": 1, "b": "2", "c": 3, "d": "4", "e": 5, "f": 6, "g": {"a": 1}}, 
+fn = (x) => typeof x === "string"
+Output: {"b":"2","d":"4"}
+Explanation: All keys with values that were not a string were removed. When the object keys were removed during the filtering process, any resulting empty objects were also removed.
+
+ +

Example 3:

+ +
+Input: 
+obj = [-1, [-1, -1, 5, -1, 10], -1, [-1], [-5]], 
+fn = (x) => x > 0
+Output: [[5,10]]
+Explanation: All values that were not greater than 0 were removed. When the values were removed during the filtering process, any resulting empty arrays were also removed.
+ +

Example 4:

+ +
+Input: 
+obj = [[[[5]]]], 
+fn = (x) => Array.isArray(x)
+Output: undefined
+
+ +

 

+

Constraints:

+ +
    +
  • fn is a function that returns a boolean value
  • +
  • obj is a valid JSON object
  • +
  • 2 <= JSON.stringify(obj).length <= 10**5
  • +
+ +## Solutions + + + +### **TypeScript** + +```ts +function deepFilter( + obj: Record, + fn: Function, +): Record | undefined { + const dfs = (data: any): any => { + if (Array.isArray(data)) { + const res = data.map(dfs).filter((item: any) => item !== undefined); + return res.length > 0 ? res : undefined; + } + if (typeof data === 'object' && data !== null) { + const res: Record = {}; + for (const key in data) { + if (data.hasOwnProperty(key)) { + const filteredValue = dfs(data[key]); + if (filteredValue !== undefined) { + res[key] = filteredValue; + } + } + } + return Object.keys(res).length > 0 ? res : undefined; + } + return fn(data) ? data : undefined; + }; + + return dfs(obj); +} +``` + + diff --git a/solution/2800-2899/2823.Deep Object Filter/Solution.ts b/solution/2800-2899/2823.Deep Object Filter/Solution.ts new file mode 100644 index 0000000000000..5de1ed69b3894 --- /dev/null +++ b/solution/2800-2899/2823.Deep Object Filter/Solution.ts @@ -0,0 +1,26 @@ +function deepFilter( + obj: Record, + fn: Function, +): Record | undefined { + const dfs = (data: any): any => { + if (Array.isArray(data)) { + const res = data.map(dfs).filter((item: any) => item !== undefined); + return res.length > 0 ? res : undefined; + } + if (typeof data === 'object' && data !== null) { + const res: Record = {}; + for (const key in data) { + if (data.hasOwnProperty(key)) { + const filteredValue = dfs(data[key]); + if (filteredValue !== undefined) { + res[key] = filteredValue; + } + } + } + return Object.keys(res).length > 0 ? res : undefined; + } + return fn(data) ? data : undefined; + }; + + return dfs(obj); +} diff --git a/solution/README.md b/solution/README.md index 468185233e18b..4ec60d9e28d25 100644 --- a/solution/README.md +++ b/solution/README.md @@ -2829,6 +2829,11 @@ | 2816 | [翻倍以链表形式表示的数字](/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/README.md) | `栈`,`链表`,`数学` | 中等 | 第 358 场周赛 | | 2817 | [限制条件下元素之间的最小绝对差](/solution/2800-2899/2817.Minimum%20Absolute%20Difference%20Between%20Elements%20With%20Constraint/README.md) | `数组`,`二分查找`,`有序集合` | 中等 | 第 358 场周赛 | | 2818 | [操作使得分最大](/solution/2800-2899/2818.Apply%20Operations%20to%20Maximize%20Score/README.md) | `栈`,`贪心`,`数组`,`数学`,`数论`,`单调栈` | 困难 | 第 358 场周赛 | +| 2819 | [Minimum Relative Loss After Buying Chocolates](/solution/2800-2899/2819.Minimum%20Relative%20Loss%20After%20Buying%20Chocolates/README.md) | | 困难 | 🔒 | +| 2820 | [Election Results](/solution/2800-2899/2820.Election%20Results/README.md) | | 中等 | 🔒 | +| 2821 | [Delay the Resolution of Each Promise](/solution/2800-2899/2821.Delay%20the%20Resolution%20of%20Each%20Promise/README.md) | | 简单 | 🔒 | +| 2822 | [Inversion of Object](/solution/2800-2899/2822.Inversion%20of%20Object/README.md) | | 简单 | 🔒 | +| 2823 | [Deep Object Filter](/solution/2800-2899/2823.Deep%20Object%20Filter/README.md) | | 中等 | 🔒 | ## 版权 diff --git a/solution/README_EN.md b/solution/README_EN.md index f0f7daefffe8a..8af80d2f21c46 100644 --- a/solution/README_EN.md +++ b/solution/README_EN.md @@ -2827,6 +2827,11 @@ Press Control+F(or Command+F on the | 2816 | [Double a Number Represented as a Linked List](/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/README_EN.md) | `Stack`,`Linked List`,`Math` | Medium | Weekly Contest 358 | | 2817 | [Minimum Absolute Difference Between Elements With Constraint](/solution/2800-2899/2817.Minimum%20Absolute%20Difference%20Between%20Elements%20With%20Constraint/README_EN.md) | `Array`,`Binary Search`,`Ordered Set` | Medium | Weekly Contest 358 | | 2818 | [Apply Operations to Maximize Score](/solution/2800-2899/2818.Apply%20Operations%20to%20Maximize%20Score/README_EN.md) | `Stack`,`Greedy`,`Array`,`Math`,`Number Theory`,`Monotonic Stack` | Hard | Weekly Contest 358 | +| 2819 | [Minimum Relative Loss After Buying Chocolates](/solution/2800-2899/2819.Minimum%20Relative%20Loss%20After%20Buying%20Chocolates/README_EN.md) | | Hard | 🔒 | +| 2820 | [Election Results](/solution/2800-2899/2820.Election%20Results/README_EN.md) | | Medium | 🔒 | +| 2821 | [Delay the Resolution of Each Promise](/solution/2800-2899/2821.Delay%20the%20Resolution%20of%20Each%20Promise/README_EN.md) | | Easy | 🔒 | +| 2822 | [Inversion of Object](/solution/2800-2899/2822.Inversion%20of%20Object/README_EN.md) | | Easy | 🔒 | +| 2823 | [Deep Object Filter](/solution/2800-2899/2823.Deep%20Object%20Filter/README_EN.md) | | Medium | 🔒 | ## Copyright diff --git a/solution/summary.md b/solution/summary.md index 6fcf53d23c217..bf6e731a0a2fb 100644 --- a/solution/summary.md +++ b/solution/summary.md @@ -2874,3 +2874,8 @@ - [2816.翻倍以链表形式表示的数字](/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/README.md) - [2817.限制条件下元素之间的最小绝对差](/solution/2800-2899/2817.Minimum%20Absolute%20Difference%20Between%20Elements%20With%20Constraint/README.md) - [2818.操作使得分最大](/solution/2800-2899/2818.Apply%20Operations%20to%20Maximize%20Score/README.md) + - [2819.Minimum Relative Loss After Buying Chocolates](/solution/2800-2899/2819.Minimum%20Relative%20Loss%20After%20Buying%20Chocolates/README.md) + - [2820.Election Results](/solution/2800-2899/2820.Election%20Results/README.md) + - [2821.Delay the Resolution of Each Promise](/solution/2800-2899/2821.Delay%20the%20Resolution%20of%20Each%20Promise/README.md) + - [2822.Inversion of Object](/solution/2800-2899/2822.Inversion%20of%20Object/README.md) + - [2823.Deep Object Filter](/solution/2800-2899/2823.Deep%20Object%20Filter/README.md) diff --git a/solution/summary_en.md b/solution/summary_en.md index a06fa37cf8eeb..27fc4f74b1a68 100644 --- a/solution/summary_en.md +++ b/solution/summary_en.md @@ -2874,3 +2874,8 @@ - [2816.Double a Number Represented as a Linked List](/solution/2800-2899/2816.Double%20a%20Number%20Represented%20as%20a%20Linked%20List/README_EN.md) - [2817.Minimum Absolute Difference Between Elements With Constraint](/solution/2800-2899/2817.Minimum%20Absolute%20Difference%20Between%20Elements%20With%20Constraint/README_EN.md) - [2818.Apply Operations to Maximize Score](/solution/2800-2899/2818.Apply%20Operations%20to%20Maximize%20Score/README_EN.md) + - [2819.Minimum Relative Loss After Buying Chocolates](/solution/2800-2899/2819.Minimum%20Relative%20Loss%20After%20Buying%20Chocolates/README_EN.md) + - [2820.Election Results](/solution/2800-2899/2820.Election%20Results/README_EN.md) + - [2821.Delay the Resolution of Each Promise](/solution/2800-2899/2821.Delay%20the%20Resolution%20of%20Each%20Promise/README_EN.md) + - [2822.Inversion of Object](/solution/2800-2899/2822.Inversion%20of%20Object/README_EN.md) + - [2823.Deep Object Filter](/solution/2800-2899/2823.Deep%20Object%20Filter/README_EN.md)