1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Leetcode #1170: Compare Strings by Frequency of the Smallest Character

Posted at
func numSmallerByFrequency(_ queries: [String], _ words: [String]) -> [Int] {
    var ar = Array(repeating: 0, count: words.count)
    for (i, word) in words.enumerated() {
        ar[i] = frequency(Array(word))
    }
    ar = ar.sorted()
    var answer = Array(repeating: 0, count: queries.count)
    for (i, query) in queries.enumerated() {
        let num = frequency(Array(query))
        answer[i] = binarySearch(ar, num)
    }
    return answer
}

private func frequency(_ str: [Character]) -> Int {
    var smallest = str[0]
    var count = 1
    for i in stride(from: 1, to: str.count, by: 1) {
        if str[i] > smallest {
            continue
        } else if str[i] < smallest {
            smallest = str[i]
            count = 1
        } else {
            count += 1
        }
    }
    return count
}

private func binarySearch(_ ar: [Int], _ num: Int) -> Int {
    var start = 0
    var end = ar.count - 1
    while start <= end {
        let mid = start + (end - start) / 2
        if ar[mid] > num {
            end = mid - 1
        } else {
            start = mid + 1
        }
    }
    return ar.count - start
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?