Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 692. Top K Frequent Words in F#

Shohei Yoshida's photo
Shohei Yoshida
·Oct 19, 2022·

1 min read

URL

leetcode.com/problems/top-k-frequent-words

Code

github.com/syohex/dotnet-study/blob/master/..

let topKFrequent (words: string list) (k: int) : string list =
    words
    |> List.fold
        (fun acc word ->
            match Map.tryFind word acc with
            | Some (n) -> Map.add word (n + 1) acc
            | None -> Map.add word 1 acc)
        Map.empty
    |> Map.toList
    |> List.sortWith (fun (word1, count1) (word2, count2) ->
        if count1 = count2 then
            compare word1 word2
        else
            compare count2 count1)
    |> List.take k
    |> List.map fst
 
Share this