Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 86. Partition List in F#

Shohei Yoshida's photo
Shohei Yoshida
·Jul 22, 2022·

1 min read

URL

leetcode.com/problems/partition-list

Code

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

type LinkedList =
    | Leaf
    | Node of int * LinkedList

    static member ofList(nums: int list) : LinkedList =
        match nums with
        | [] -> Leaf
        | h :: t -> Node(h, LinkedList.ofList t)

let partition (head: LinkedList) (x: int) : LinkedList =
    let rec partition' node x lowers highers =
        match node with
        | Leaf ->
            let nums =
                (lowers |> List.rev) @ (highers |> List.rev)

            LinkedList.ofList nums
        | Node (v, next) ->
            if v < x then
                partition' next x (v :: lowers) highers
            else
                partition' next x lowers (v :: highers)

    partition' head x [] []
 
Share this