1170. Compare Strings by Frequency of the Smallest Character

26 年 2 月 25 日 星期三
218 字
2 分钟

1170. Compare Strings by Frequency of the Smallest Character

Screenshot 2026-02-25 at 11.05.54 pm

读懂题就不难了,直接在queries里面存f 处理过的函数,可以将string转换成UTF code,用Math.min 找到最小值出现了几次,之后直接二分就行。

代码的注意点:

const min = Math.min(...arr) 这里要用spread展开

item.charCodeAt(0) 转换成 UTF-16 code

ts
function numSmallerByFrequency(queries: string[], words: string[]): number[] {
  const f = (arr: number[]): number => {
    const min = Math.min(...arr)
    return arr.filter((item) => {
      if (item === min) {
        return true
      }
    }).length
  }
  const binarySearch = (left, right, target, arr) => {
    while (left < right) {
      const mid = Math.floor((left + right) / 2)
      if (arr[mid] < target) {
        left = mid + 1
      } else {
        right = mid
      }
    }
    return left
  }

  const ans = []
  const newQueries = []
  const newWords = []
  queries.forEach((item) => {
    const strArray = item.split('')
    newQueries.push(f(strArray.map((item) => item.charCodeAt(0))))
  })
  words.forEach((item) => {
    const strArray = item.split('')
    newWords.push(f(strArray.map((item) => item.charCodeAt(0))))
  })

  newWords.sort((a, b) => a - b)
  for (const i of newQueries) {
    ans.push(newWords.length - binarySearch(0, newWords.length, i + 1, newWords))
  }
  return ans
}

文章标题:1170. Compare Strings by Frequency of the Smallest Character

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/1170_compare_strings_by_frequency_of_the_smallest_character[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。