File tree Expand file tree Collapse file tree 3 files changed +6
-12
lines changed
solution/1100-1199/1170.Compare Strings by Frequency of the Smallest Character Expand file tree Collapse file tree 3 files changed +6
-12
lines changed Original file line number Diff line number Diff line change 51
51
52
52
我们先按照题目描述,实现函数 $f(s)$,函数返回字符串 $s$ 中按字典序比较最小字母的出现频次。
53
53
54
- 接下来,我们将 $words$ 中的每个字符串 $s $ 都计算出 $f(s )$,并将其排序,存放在数组 $arr $ 中。
54
+ 接下来,我们将 $words$ 中的每个字符串 $w $ 都计算出 $f(w )$,并将其排序,存放在数组 $nums $ 中。
55
55
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$。
57
57
58
- 时间复杂度 $O(n \times \log n )$,空间复杂度 $O(n)$。其中 $n$ 为 $ words$ 的长度。
58
+ 时间复杂度 $O((n + q) \times M )$,空间复杂度 $O(n)$。其中 $n$ 和 $q$ 分别是数组 $ words$ 和 $queries$ 的长度,而 $M$ 是字符串的最大长度 。
59
59
60
60
<!-- tabs:start -->
61
61
@@ -68,9 +68,7 @@ class Solution:
68
68
def numSmallerByFrequency (self , queries : List[str ], words : List[str ]) -> List[int ]:
69
69
def f (s : str ) -> int :
70
70
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])
74
72
75
73
n = len (words)
76
74
nums = sorted (f(w) for w in words)
Original file line number Diff line number Diff line change @@ -48,9 +48,7 @@ class Solution:
48
48
def numSmallerByFrequency (self , queries : List[str ], words : List[str ]) -> List[int ]:
49
49
def f (s : str ) -> int :
50
50
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])
54
52
55
53
n = len (words)
56
54
nums = sorted (f(w) for w in words)
Original file line number Diff line number Diff line change @@ -2,9 +2,7 @@ class Solution:
2
2
def numSmallerByFrequency (self , queries : List [str ], words : List [str ]) -> List [int ]:
3
3
def f (s : str ) -> int :
4
4
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 ])
8
6
9
7
n = len (words )
10
8
nums = sorted (f (w ) for w in words )
You can’t perform that action at this time.
0 commit comments