Re: [閒聊] 每日leetcode

作者: JIWP (JIWP)   2024-09-08 22:19:34
725. Split Linked List in Parts
給一個linked list,和一個整數k
請將這個linked list分成k個linked list
並且用一個矩陣記錄每一個linked list的head
每個linked list的長度不能相差超過1
且較長的要放前面
思路 :
用一個矩陣紀錄每一個node
接著就開始分成k等分
滿簡單的
golang code :
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func splitListToParts(head *ListNode, k int) []*ListNode {
rec := make([]*ListNode, 0)
for head != nil {
rec = append(rec, head)
head = head.Next
}
n := len(rec)
res := make([]*ListNode, k)
if k > n {
for i := 0; i < n; i++ {
res[i] = rec[i]
rec[i].Next = nil
}
return res
}
idx, remainder, num := 0, n%k, n/k
for i := 0; i < k; i++ {
res[i] = rec[idx]
if remainder > 0 {
idx += num + 1
rec[idx-1].Next = nil
remainder
作者: sustainer123 (caster)   2023-09-08 22:19:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com