diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README.md b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README.md index 8e86fae398f1d..6ea9e375205e8 100644 --- a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README.md +++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README.md @@ -65,7 +65,7 @@ 最后我们返回答案即可。 -时间复杂度为 $O(n^2)$,其中 $n$ 是字符串 $s$ 的长度。 +时间复杂度 $O(n^2)$,空间复杂度 $O(n^2)$,其中 $n$ 为字符串 $s$ 的长度。 @@ -82,11 +82,11 @@ class Solution: for i in range(n): f[i][i] = 1 ans = 0 - for i in range(n - 1, -1, -1): + for i in range(n - 2, -1, -1): for j in range(i + 1, n): if s[i] == s[j]: f[i][j] = f[i + 1][j - 1] + 2 - if i < len(word1) and j >= len(word1): + if i < len(word1) <= j: ans = max(ans, f[i][j]) else: f[i][j] = max(f[i + 1][j], f[i][j - 1]) @@ -180,6 +180,62 @@ func longestPalindrome(word1 string, word2 string) (ans int) { } ``` +### **TypeScript** + +```ts +function longestPalindrome(word1: string, word2: string): number { + const s = word1 + word2; + const n = s.length; + const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); + for (let i = 0; i < n; ++i) { + f[i][i] = 1; + } + let ans = 0; + for (let i = n - 2; ~i; --i) { + for (let j = i + 1; j < n; ++j) { + if (s[i] === s[j]) { + f[i][j] = f[i + 1][j - 1] + 2; + if (i < word1.length && j >= word1.length) { + ans = Math.max(ans, f[i][j]); + } + } else { + f[i][j] = Math.max(f[i + 1][j], f[i][j - 1]); + } + } + } + return ans; +} +``` + +### **Rust** + +```rust +impl Solution { + pub fn longest_palindrome(word1: String, word2: String) -> i32 { + let s: Vec = format!("{}{}", word1, word2).chars().collect(); + let n = s.len(); + let mut f = vec![vec![0; n]; n]; + for i in 0..n { + f[i][i] = 1; + } + let mut ans = 0; + for i in (0..n - 1).rev() { + for j in i + 1..n { + if s[i] == s[j] { + f[i][j] = f[i + 1][j - 1] + 2; + if i < word1.len() && j >= word1.len() { + ans = ans.max(f[i][j]); + } + } else { + f[i][j] = f[i + 1][j].max(f[i][j - 1]); + } + } + } + ans + } +} +``` + ### **...** ``` diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md index c9e25ab9b7887..729f1e7db4d42 100644 --- a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md +++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/README_EN.md @@ -50,6 +50,20 @@ ## Solutions +**Solution 1: Dynamic Programming** + +First, we concatenate strings `word1` and `word2` to get string $s$. Then we can transform the problem into finding the length of the longest palindromic subsequence in string $s$. However, when calculating the final answer, we need to ensure that at least one character in the palindrome string comes from `word1` and another character comes from `word2`. + +We define $f[i][j]$ as the length of the longest palindromic subsequence in the substring of string $s$ with index range $[i, j]$. + +If $s[i] = s[j]$, then $s[i]$ and $s[j]$ must be in the longest palindromic subsequence, at this time $f[i][j] = f[i + 1][j - 1] + 2$. At this point, we also need to judge whether $s[i]$ and $s[j]$ come from `word1` and `word2`. If so, we update the maximum value of the answer to $ans=\max(ans, f[i][j])$. + +If $s[i] \neq s[j]$, then $s[i]$ and $s[j]$ will definitely not appear in the longest palindromic subsequence at the same time, at this time $f[i][j] = max(f[i + 1][j], f[i][j - 1])$. + +Finally, we return the answer. + +The time complexity is $O(n^2)$, and the space complexity is $O(n^2)$. Here, $n$ is the length of string $s$. + ### **Python3** @@ -63,11 +77,11 @@ class Solution: for i in range(n): f[i][i] = 1 ans = 0 - for i in range(n - 1, -1, -1): + for i in range(n - 2, -1, -1): for j in range(i + 1, n): if s[i] == s[j]: f[i][j] = f[i + 1][j - 1] + 2 - if i < len(word1) and j >= len(word1): + if i < len(word1) <= j: ans = max(ans, f[i][j]) else: f[i][j] = max(f[i + 1][j], f[i][j - 1]) @@ -159,6 +173,62 @@ func longestPalindrome(word1 string, word2 string) (ans int) { } ``` +### **TypeScript** + +```ts +function longestPalindrome(word1: string, word2: string): number { + const s = word1 + word2; + const n = s.length; + const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); + for (let i = 0; i < n; ++i) { + f[i][i] = 1; + } + let ans = 0; + for (let i = n - 2; ~i; --i) { + for (let j = i + 1; j < n; ++j) { + if (s[i] === s[j]) { + f[i][j] = f[i + 1][j - 1] + 2; + if (i < word1.length && j >= word1.length) { + ans = Math.max(ans, f[i][j]); + } + } else { + f[i][j] = Math.max(f[i + 1][j], f[i][j - 1]); + } + } + } + return ans; +} +``` + +### **Rust** + +```rust +impl Solution { + pub fn longest_palindrome(word1: String, word2: String) -> i32 { + let s: Vec = format!("{}{}", word1, word2).chars().collect(); + let n = s.len(); + let mut f = vec![vec![0; n]; n]; + for i in 0..n { + f[i][i] = 1; + } + let mut ans = 0; + for i in (0..n - 1).rev() { + for j in i + 1..n { + if s[i] == s[j] { + f[i][j] = f[i + 1][j - 1] + 2; + if i < word1.len() && j >= word1.len() { + ans = ans.max(f[i][j]); + } + } else { + f[i][j] = f[i + 1][j].max(f[i][j - 1]); + } + } + } + ans + } +} +``` + ### **...** ``` diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.py b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.py index 4d9d9060c4de1..9980153e69e14 100644 --- a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.py +++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.py @@ -1,17 +1,17 @@ -class Solution: - def longestPalindrome(self, word1: str, word2: str) -> int: - s = word1 + word2 - n = len(s) - f = [[0] * n for _ in range(n)] - for i in range(n): - f[i][i] = 1 - ans = 0 - for i in range(n - 1, -1, -1): - for j in range(i + 1, n): - if s[i] == s[j]: - f[i][j] = f[i + 1][j - 1] + 2 - if i < len(word1) and j >= len(word1): - ans = max(ans, f[i][j]) - else: - f[i][j] = max(f[i + 1][j], f[i][j - 1]) - return ans +class Solution: + def longestPalindrome(self, word1: str, word2: str) -> int: + s = word1 + word2 + n = len(s) + f = [[0] * n for _ in range(n)] + for i in range(n): + f[i][i] = 1 + ans = 0 + for i in range(n - 2, -1, -1): + for j in range(i + 1, n): + if s[i] == s[j]: + f[i][j] = f[i + 1][j - 1] + 2 + if i < len(word1) <= j: + ans = max(ans, f[i][j]) + else: + f[i][j] = max(f[i + 1][j], f[i][j - 1]) + return ans diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.rs b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.rs new file mode 100644 index 0000000000000..2e4b9ac26d36b --- /dev/null +++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.rs @@ -0,0 +1,24 @@ +impl Solution { + pub fn longest_palindrome(word1: String, word2: String) -> i32 { + let s: Vec = format!("{}{}", word1, word2).chars().collect(); + let n = s.len(); + let mut f = vec![vec![0; n]; n]; + for i in 0..n { + f[i][i] = 1; + } + let mut ans = 0; + for i in (0..n - 1).rev() { + for j in i + 1..n { + if s[i] == s[j] { + f[i][j] = f[i + 1][j - 1] + 2; + if i < word1.len() && j >= word1.len() { + ans = ans.max(f[i][j]); + } + } else { + f[i][j] = f[i + 1][j].max(f[i][j - 1]); + } + } + } + ans + } +} diff --git a/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.ts b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.ts new file mode 100644 index 0000000000000..161819205ea0e --- /dev/null +++ b/solution/1700-1799/1771.Maximize Palindrome Length From Subsequences/Solution.ts @@ -0,0 +1,22 @@ +function longestPalindrome(word1: string, word2: string): number { + const s = word1 + word2; + const n = s.length; + const f: number[][] = Array.from({ length: n }, () => Array.from({ length: n }, () => 0)); + for (let i = 0; i < n; ++i) { + f[i][i] = 1; + } + let ans = 0; + for (let i = n - 2; ~i; --i) { + for (let j = i + 1; j < n; ++j) { + if (s[i] === s[j]) { + f[i][j] = f[i + 1][j - 1] + 2; + if (i < word1.length && j >= word1.length) { + ans = Math.max(ans, f[i][j]); + } + } else { + f[i][j] = Math.max(f[i + 1][j], f[i][j - 1]); + } + } + } + return ans; +} diff --git a/solution/1700-1799/1772.Sort Features by Popularity/README.md b/solution/1700-1799/1772.Sort Features by Popularity/README.md index 70479184f63b4..762b662cc1fd7 100644 --- a/solution/1700-1799/1772.Sort Features by Popularity/README.md +++ b/solution/1700-1799/1772.Sort Features by Popularity/README.md @@ -51,7 +51,7 @@ **方法一:哈希表 + 自定义排序** -我们遍历 `responses`,对于 `responses[i]` 中的每个单词,我们用一个哈希表 `ws` 暂存。接下来将 `ws` 中的单词记录到哈希表 `cnt` 中,记录每个单词出现的次数。 +我们遍历 `responses`,对于 `responses[i]` 中的每个单词,我们用一个哈希表 `vis` 暂存。接下来将 `vis` 中的单词记录到哈希表 `cnt` 中,记录每个单词出现的次数。 接下来,采用自定义排序,将 `features` 中的单词按照出现次数从大到小排序,如果出现次数相同,则按照出现的下标从小到大排序。 @@ -67,11 +67,10 @@ class Solution: def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]: cnt = Counter() - for r in responses: - ws = set(r.split()) - for s in ws: - cnt[s] += 1 - return sorted(features, key=lambda x: -cnt[x]) + for s in responses: + for w in set(s.split()): + cnt[w] += 1 + return sorted(features, key=lambda w: -cnt[w]) ``` ### **Java** @@ -82,26 +81,26 @@ class Solution: class Solution { public String[] sortFeatures(String[] features, String[] responses) { Map cnt = new HashMap<>(); - for (String r : responses) { - Set ws = new HashSet<>(); - for (String w : r.split(" ")) { - ws.add(w); - } - for (String w : ws) { - cnt.put(w, cnt.getOrDefault(w, 0) + 1); + for (String s : responses) { + Set vis = new HashSet<>(); + for (String w : s.split(" ")) { + if (vis.add(w)) { + cnt.merge(w, 1, Integer::sum); + } } } int n = features.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; i++) { idx[i] = i; } Arrays.sort(idx, (i, j) -> { - int d = cnt.getOrDefault(features[j], 0) - cnt.getOrDefault(features[i], 0); - return d == 0 ? i - j : d; + int x = cnt.getOrDefault(features[i], 0); + int y = cnt.getOrDefault(features[j], 0); + return x == y ? i - j : y - x; }); String[] ans = new String[n]; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; i++) { ans[i] = features[idx[i]]; } return ans; @@ -116,23 +115,23 @@ class Solution { public: vector sortFeatures(vector& features, vector& responses) { unordered_map cnt; - for (auto& r : responses) { - stringstream ss(r); - string t; - unordered_set ws; - while (ss >> t) { - ws.insert(t); + for (auto& s : responses) { + istringstream iss(s); + string w; + unordered_set st; + while (iss >> w) { + st.insert(w); } - for (auto& w : ws) { - cnt[w]++; + for (auto& w : st) { + ++cnt[w]; } } int n = features.size(); vector idx(n); iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) -> bool { - int d = cnt[features[i]] - cnt[features[j]]; - return d > 0 || (d == 0 && i < j); + sort(idx.begin(), idx.end(), [&](int i, int j) { + int x = cnt[features[i]], y = cnt[features[j]]; + return x == y ? i < j : x > y; }); vector ans(n); for (int i = 0; i < n; ++i) { @@ -148,29 +147,43 @@ public: ```go func sortFeatures(features []string, responses []string) []string { cnt := map[string]int{} - for _, r := range responses { - ws := map[string]bool{} - for _, s := range strings.Split(r, " ") { - ws[s] = true - } - for w := range ws { - cnt[w]++ + for _, s := range responses { + vis := map[string]bool{} + for _, w := range strings.Split(s, " ") { + if !vis[w] { + cnt[w]++ + vis[w] = true + } } } - n := len(features) - idx := make([]int, n) - for i := range idx { - idx[i] = i - } - sort.Slice(idx, func(i, j int) bool { - d := cnt[features[idx[i]]] - cnt[features[idx[j]]] - return d > 0 || (d == 0 && idx[i] < idx[j]) - }) - ans := make([]string, n) - for i := range ans { - ans[i] = features[idx[i]] - } - return ans + sort.SliceStable(features, func(i, j int) bool { return cnt[features[i]] > cnt[features[j]] }) + return features +} +``` + +### **TypeScript** + +```ts +function sortFeatures(features: string[], responses: string[]): string[] { + const cnt: Map = new Map(); + for (const s of responses) { + const vis: Set = new Set(); + for (const w of s.split(' ')) { + if (vis.has(w)) { + continue; + } + vis.add(w); + cnt.set(w, (cnt.get(w) || 0) + 1); + } + } + const n = features.length; + const idx: number[] = Array.from({ length: n }, (_, i) => i); + idx.sort((i, j) => { + const x = cnt.get(features[i]) || 0; + const y = cnt.get(features[j]) || 0; + return x === y ? i - j : y - x; + }); + return idx.map(i => features[i]); } ``` diff --git a/solution/1700-1799/1772.Sort Features by Popularity/README_EN.md b/solution/1700-1799/1772.Sort Features by Popularity/README_EN.md index fa61ea0f4914a..d8849be99f6b0 100644 --- a/solution/1700-1799/1772.Sort Features by Popularity/README_EN.md +++ b/solution/1700-1799/1772.Sort Features by Popularity/README_EN.md @@ -43,6 +43,14 @@ ## Solutions +**Solution 1: Hash Table + Custom Sorting** + +We traverse `responses`, and for each word in `responses[i]`, we temporarily store it in a hash table `vis`. Next, we record the words in `vis` into the hash table `cnt`, recording the number of times each word appears. + +Next, we use custom sorting to sort the words in `features` in descending order of occurrence. If the number of occurrences is the same, we sort them in ascending order of the index where they appear. + +The time complexity is $O(n \times \log n)$, where $n$ is the length of `features`. + ### **Python3** @@ -51,11 +59,10 @@ class Solution: def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]: cnt = Counter() - for r in responses: - ws = set(r.split()) - for s in ws: - cnt[s] += 1 - return sorted(features, key=lambda x: -cnt[x]) + for s in responses: + for w in set(s.split()): + cnt[w] += 1 + return sorted(features, key=lambda w: -cnt[w]) ``` ### **Java** @@ -64,26 +71,26 @@ class Solution: class Solution { public String[] sortFeatures(String[] features, String[] responses) { Map cnt = new HashMap<>(); - for (String r : responses) { - Set ws = new HashSet<>(); - for (String w : r.split(" ")) { - ws.add(w); - } - for (String w : ws) { - cnt.put(w, cnt.getOrDefault(w, 0) + 1); + for (String s : responses) { + Set vis = new HashSet<>(); + for (String w : s.split(" ")) { + if (vis.add(w)) { + cnt.merge(w, 1, Integer::sum); + } } } int n = features.length; Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; i++) { idx[i] = i; } Arrays.sort(idx, (i, j) -> { - int d = cnt.getOrDefault(features[j], 0) - cnt.getOrDefault(features[i], 0); - return d == 0 ? i - j : d; + int x = cnt.getOrDefault(features[i], 0); + int y = cnt.getOrDefault(features[j], 0); + return x == y ? i - j : y - x; }); String[] ans = new String[n]; - for (int i = 0; i < n; ++i) { + for (int i = 0; i < n; i++) { ans[i] = features[idx[i]]; } return ans; @@ -98,23 +105,23 @@ class Solution { public: vector sortFeatures(vector& features, vector& responses) { unordered_map cnt; - for (auto& r : responses) { - stringstream ss(r); - string t; - unordered_set ws; - while (ss >> t) { - ws.insert(t); + for (auto& s : responses) { + istringstream iss(s); + string w; + unordered_set st; + while (iss >> w) { + st.insert(w); } - for (auto& w : ws) { - cnt[w]++; + for (auto& w : st) { + ++cnt[w]; } } int n = features.size(); vector idx(n); iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) -> bool { - int d = cnt[features[i]] - cnt[features[j]]; - return d > 0 || (d == 0 && i < j); + sort(idx.begin(), idx.end(), [&](int i, int j) { + int x = cnt[features[i]], y = cnt[features[j]]; + return x == y ? i < j : x > y; }); vector ans(n); for (int i = 0; i < n; ++i) { @@ -130,29 +137,43 @@ public: ```go func sortFeatures(features []string, responses []string) []string { cnt := map[string]int{} - for _, r := range responses { - ws := map[string]bool{} - for _, s := range strings.Split(r, " ") { - ws[s] = true + for _, s := range responses { + vis := map[string]bool{} + for _, w := range strings.Split(s, " ") { + if !vis[w] { + cnt[w]++ + vis[w] = true + } } - for w := range ws { - cnt[w]++ - } - } - n := len(features) - idx := make([]int, n) - for i := range idx { - idx[i] = i } - sort.Slice(idx, func(i, j int) bool { - d := cnt[features[idx[i]]] - cnt[features[idx[j]]] - return d > 0 || (d == 0 && idx[i] < idx[j]) - }) - ans := make([]string, n) - for i := range ans { - ans[i] = features[idx[i]] - } - return ans + sort.SliceStable(features, func(i, j int) bool { return cnt[features[i]] > cnt[features[j]] }) + return features +} +``` + +### **TypeScript** + +```ts +function sortFeatures(features: string[], responses: string[]): string[] { + const cnt: Map = new Map(); + for (const s of responses) { + const vis: Set = new Set(); + for (const w of s.split(' ')) { + if (vis.has(w)) { + continue; + } + vis.add(w); + cnt.set(w, (cnt.get(w) || 0) + 1); + } + } + const n = features.length; + const idx: number[] = Array.from({ length: n }, (_, i) => i); + idx.sort((i, j) => { + const x = cnt.get(features[i]) || 0; + const y = cnt.get(features[j]) || 0; + return x === y ? i - j : y - x; + }); + return idx.map(i => features[i]); } ``` diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.cpp b/solution/1700-1799/1772.Sort Features by Popularity/Solution.cpp index 18bb88ca04f5a..dba4a4c39152e 100644 --- a/solution/1700-1799/1772.Sort Features by Popularity/Solution.cpp +++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.cpp @@ -1,29 +1,29 @@ -class Solution { -public: - vector sortFeatures(vector& features, vector& responses) { - unordered_map cnt; - for (auto& r : responses) { - stringstream ss(r); - string t; - unordered_set ws; - while (ss >> t) { - ws.insert(t); - } - for (auto& w : ws) { - cnt[w]++; - } - } - int n = features.size(); - vector idx(n); - iota(idx.begin(), idx.end(), 0); - sort(idx.begin(), idx.end(), [&](int i, int j) -> bool { - int d = cnt[features[i]] - cnt[features[j]]; - return d > 0 || (d == 0 && i < j); - }); - vector ans(n); - for (int i = 0; i < n; ++i) { - ans[i] = features[idx[i]]; - } - return ans; - } +class Solution { +public: + vector sortFeatures(vector& features, vector& responses) { + unordered_map cnt; + for (auto& s : responses) { + istringstream iss(s); + string w; + unordered_set st; + while (iss >> w) { + st.insert(w); + } + for (auto& w : st) { + ++cnt[w]; + } + } + int n = features.size(); + vector idx(n); + iota(idx.begin(), idx.end(), 0); + sort(idx.begin(), idx.end(), [&](int i, int j) { + int x = cnt[features[i]], y = cnt[features[j]]; + return x == y ? i < j : x > y; + }); + vector ans(n); + for (int i = 0; i < n; ++i) { + ans[i] = features[idx[i]]; + } + return ans; + } }; \ No newline at end of file diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.go b/solution/1700-1799/1772.Sort Features by Popularity/Solution.go index d17126fc85a43..5e0504ca80658 100644 --- a/solution/1700-1799/1772.Sort Features by Popularity/Solution.go +++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.go @@ -1,26 +1,14 @@ func sortFeatures(features []string, responses []string) []string { cnt := map[string]int{} - for _, r := range responses { - ws := map[string]bool{} - for _, s := range strings.Split(r, " ") { - ws[s] = true + for _, s := range responses { + vis := map[string]bool{} + for _, w := range strings.Split(s, " ") { + if !vis[w] { + cnt[w]++ + vis[w] = true + } } - for w := range ws { - cnt[w]++ - } - } - n := len(features) - idx := make([]int, n) - for i := range idx { - idx[i] = i - } - sort.Slice(idx, func(i, j int) bool { - d := cnt[features[idx[i]]] - cnt[features[idx[j]]] - return d > 0 || (d == 0 && idx[i] < idx[j]) - }) - ans := make([]string, n) - for i := range ans { - ans[i] = features[idx[i]] } - return ans + sort.SliceStable(features, func(i, j int) bool { return cnt[features[i]] > cnt[features[j]] }) + return features } \ No newline at end of file diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.java b/solution/1700-1799/1772.Sort Features by Popularity/Solution.java index cbb1d31ac3c3c..702a7979d845f 100644 --- a/solution/1700-1799/1772.Sort Features by Popularity/Solution.java +++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.java @@ -1,28 +1,28 @@ -class Solution { - public String[] sortFeatures(String[] features, String[] responses) { - Map cnt = new HashMap<>(); - for (String r : responses) { - Set ws = new HashSet<>(); - for (String w : r.split(" ")) { - ws.add(w); - } - for (String w : ws) { - cnt.put(w, cnt.getOrDefault(w, 0) + 1); - } - } - int n = features.length; - Integer[] idx = new Integer[n]; - for (int i = 0; i < n; ++i) { - idx[i] = i; - } - Arrays.sort(idx, (i, j) -> { - int d = cnt.getOrDefault(features[j], 0) - cnt.getOrDefault(features[i], 0); - return d == 0 ? i - j : d; - }); - String[] ans = new String[n]; - for (int i = 0; i < n; ++i) { - ans[i] = features[idx[i]]; - } - return ans; - } +class Solution { + public String[] sortFeatures(String[] features, String[] responses) { + Map cnt = new HashMap<>(); + for (String s : responses) { + Set vis = new HashSet<>(); + for (String w : s.split(" ")) { + if (vis.add(w)) { + cnt.merge(w, 1, Integer::sum); + } + } + } + int n = features.length; + Integer[] idx = new Integer[n]; + for (int i = 0; i < n; i++) { + idx[i] = i; + } + Arrays.sort(idx, (i, j) -> { + int x = cnt.getOrDefault(features[i], 0); + int y = cnt.getOrDefault(features[j], 0); + return x == y ? i - j : y - x; + }); + String[] ans = new String[n]; + for (int i = 0; i < n; i++) { + ans[i] = features[idx[i]]; + } + return ans; + } } \ No newline at end of file diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.py b/solution/1700-1799/1772.Sort Features by Popularity/Solution.py index f2bd217e047a8..5250bc917eb10 100644 --- a/solution/1700-1799/1772.Sort Features by Popularity/Solution.py +++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.py @@ -1,8 +1,7 @@ -class Solution: - def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]: - cnt = Counter() - for r in responses: - ws = set(r.split()) - for s in ws: - cnt[s] += 1 - return sorted(features, key=lambda x: -cnt[x]) +class Solution: + def sortFeatures(self, features: List[str], responses: List[str]) -> List[str]: + cnt = Counter() + for s in responses: + for w in set(s.split()): + cnt[w] += 1 + return sorted(features, key=lambda w: -cnt[w]) diff --git a/solution/1700-1799/1772.Sort Features by Popularity/Solution.ts b/solution/1700-1799/1772.Sort Features by Popularity/Solution.ts new file mode 100644 index 0000000000000..1a6ac9ce17b54 --- /dev/null +++ b/solution/1700-1799/1772.Sort Features by Popularity/Solution.ts @@ -0,0 +1,21 @@ +function sortFeatures(features: string[], responses: string[]): string[] { + const cnt: Map = new Map(); + for (const s of responses) { + const vis: Set = new Set(); + for (const w of s.split(' ')) { + if (vis.has(w)) { + continue; + } + vis.add(w); + cnt.set(w, (cnt.get(w) || 0) + 1); + } + } + const n = features.length; + const idx: number[] = Array.from({ length: n }, (_, i) => i); + idx.sort((i, j) => { + const x = cnt.get(features[i]) || 0; + const y = cnt.get(features[j]) || 0; + return x === y ? i - j : y - x; + }); + return idx.map(i => features[i]); +}