LeetCode 532. K-diff Pairs in an Array in F#

URL

leetcode.com/problems/k-diff-pairs-in-an-ar..

Code

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

let toMap (nums: int list) : Map<int, int> =
    let rec toMap' nums m =
        match nums with
        | [] -> m
        | head :: tail ->
            match Map.tryFind head m with
            | Some v -> toMap' tail (Map.add head (v + 1) m)
            | None -> toMap' tail (Map.add head 1 m)

    toMap' nums Map.empty

let findPairs (nums: int list) (k: int) : int =
    let rec findPairs' keys k m acc =
        match keys with
        | [] -> acc
        | head :: tail ->
            match Map.tryFind (head - k) m with
            | None -> findPairs' tail k m acc
            | Some v ->
                if k = 0 then
                    if v >= 2 then
                        findPairs' tail k m (acc + 1)
                    else
                        findPairs' tail k m acc
                else
                    findPairs' tail k m (acc + 1)

    let m = toMap nums
    findPairs' (m |> Map.keys |> Seq.toList) k m 0