一.问题描述
Let's define a function f(s)
over a non-empty string s
, which calculates the frequency of the smallest character in s
. For example, if s = "dcce"
then f(s) = 2
because the smallest character is "c"
and its frequency is 2.
Now, given string arrays queries
and words
, return an integer array answer
, where each answer[i]
is the number of words such that f(queries[i])
< f(W)
, where W
is a word in words
.
Example 1:
Input: queries = ["cbd"], words = ["zaaaz"] Output: [1] Explanation: On the first query we have f("cbd") = 1, f("zaaaz") = 3 so f("cbd") < f("zaaaz").
Example 2:
Input: queries = ["bbb","cc"], words = ["a","aa","aaa","aaaa"] Output: [1,2] Explanation: On the first query only f("bbb") < f("aaaa"). On the second query both f("aaa") and f("aaaa") are both > f("cc").
Constraints:
1 <= queries.length <= 2000
1 <= words.length <= 2000
1 <= queries[i].length, words[i].length <= 10
queries[i][j]
,words[i][j]
are English lowercase letters.
二.解题思路
这道题就是中规中矩的走,由于leetcode限制比较松,如果你写的好的话,不用二分搜索也能过。
首先计算queries里的每个min,然后再计算words里的每个min,最后遍历每个query和words比对。
我们可以计算一下时间复杂度。
假设queries长为m,words长为n,那么时间复杂度就是O(mn)。
虽然leetcode比较松,但是如果你写的不好有很多多余的操作的话,就会TLE。
其实这道题最好使用二分查找做,把words的min数组排序。然后遍历query的时候用二分查找。
时间复杂度是O(mlogn).
如果你对二分查找不熟悉,建议自己写,如果很熟你可以直接引用库函数。
自己写的时候注意二分查找的返回的坐标含义,是小于该坐标的值全都大于target还是全都大于等于target。根据不同问题得自己弄明白。
我把三个版本都贴上仅供参考。
更多leetcode算法题解法请关注我的专栏leetcode算法从零到结束或关注我
欢迎大家一起套路一起刷题一起ac。
三.源码
1.自己动手写二分查找
class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
len_w=len(words)
def binSearch(arr, target):
left,right=0,len(arr)-1
while left<=right:
mid=int((left+right)/2)
if target>=arr[mid]:
left=mid+1
elif target<arr[mid]:
right=mid-1
return left
cnts_w_min=sorted([word.count(min(word)) for word in words])
cnts_q_min=[query.count(min(query)) for query in queries]
return [len_w-binSearch(cnts_w_min,cnt_q) for cnt_q in cnts_q_min]
2.库函数
库函数的bisect比自己实现的要快一些,这就很尴尬了,难道用了什么高大上的东西。
from bisect import bisect
class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
len_w=len(words)
cnts_w_min=sorted([word.count(min(word)) for word in words])
cnts_q_min=[query.count(min(query)) for query in queries]
return [len_w-bisect(cnts_w_min,cnt_q) for cnt_q in cnts_q_min]
3.不用二分查找
class Solution:
def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
cnts_w_min=[word.count(min(word)) for word in words]
cnts_q_min=[query.count(min(query)) for query in queries]
return [sum([cnt_q<cnt_w for cnt_w in cnts_w_min]) for cnt_q in cnts_q_min]