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
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme