Skip to content

Commit ccfc0bf

Browse files
committed
feat: update solutions to lc problem: No.1170
No.1170.Compare Strings by Frequency of the Smallest Character
1 parent f2fa675 commit ccfc0bf

File tree

3 files changed

+6
-12
lines changed

3 files changed

+6
-12
lines changed

solution/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README.md

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -51,11 +51,11 @@
5151

5252
我们先按照题目描述,实现函数 $f(s)$,函数返回字符串 $s$ 中按字典序比较最小字母的出现频次。
5353

54-
接下来,我们将 $words$ 中的每个字符串 $s$ 都计算出 $f(s)$,并将其排序,存放在数组 $arr$ 中。
54+
接下来,我们将 $words$ 中的每个字符串 $w$ 都计算出 $f(w)$,并将其排序,存放在数组 $nums$ 中。
5555

56-
最后,我们遍历 $queries$ 中的每个字符串 $s$,计算 $f(s)$,然后在 $arr$ 中二分查找第一个大于 $f(s)$ 的位置 $i$,则 $arr$ 中下标 $i$ 及其后面的元素都满足 $f(s) < f(W)$,其中 $W$ 表示 $words$ 中的每个字符串,因此当前查询的答案就是 $n - i$。
56+
然后,我们遍历 $queries$ 中的每个字符串 $q$,在 $nums$ 中二分查找第一个大于 $f(q)$ 的位置 $i$,则 $nums$ 中下标 $i$ 及其后面的元素都满足 $f(q) < f(W)$,那么当前查询的答案就是 $n - i$。
5757

58-
时间复杂度 $O(n \times \log n)$,空间复杂度 $O(n)$。其中 $n$ 为 $words$ 的长度。
58+
时间复杂度 $O((n + q) \times M)$,空间复杂度 $O(n)$。其中 $n$ 和 $q$ 分别是数组 $words$ 和 $queries$ 的长度,而 $M$ 是字符串的最大长度
5959

6060
<!-- tabs:start -->
6161

@@ -68,9 +68,7 @@ class Solution:
6868
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
6969
def f(s: str) -> int:
7070
cnt = Counter(s)
71-
for c in ascii_lowercase:
72-
if x := cnt[c]:
73-
return x
71+
return next(cnt[c] for c in ascii_lowercase if cnt[c])
7472

7573
n = len(words)
7674
nums = sorted(f(w) for w in words)

solution/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/README_EN.md

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,7 @@ class Solution:
4848
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
4949
def f(s: str) -> int:
5050
cnt = Counter(s)
51-
for c in ascii_lowercase:
52-
if x := cnt[c]:
53-
return x
51+
return next(cnt[c] for c in ascii_lowercase if cnt[c])
5452

5553
n = len(words)
5654
nums = sorted(f(w) for w in words)

solution/1100-1199/1170.Compare Strings by Frequency of the Smallest Character/Solution.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@ class Solution:
22
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
33
def f(s: str) -> int:
44
cnt = Counter(s)
5-
for c in ascii_lowercase:
6-
if x := cnt[c]:
7-
return x
5+
return next(cnt[c] for c in ascii_lowercase if cnt[c])
86

97
n = len(words)
108
nums = sorted(f(w) for w in words)

0 commit comments

Comments
 (0)