栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

leetcode 725. Split Linked List in Parts | 725. 分隔链表(Java)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode 725. Split Linked List in Parts | 725. 分隔链表(Java)

题目

https://leetcode.com/problems/split-linked-list-in-parts/

题解

hint: If there are N nodes in the list, and k parts, then every part has N/k elements, except the first N%k parts have an extra one.

class Solution {
    public ListNode[] splitListToParts(ListNode head, int k) {
        // 例1: 长度为10的链表, 分成3段, [4 3 3]
        //      其中,10%3=1段长度为4, 3-1=2段长度为3
        // 例2: 长度为11的链表, 分成3段, [4 4 3]
        //      其中,11%3=2段长度为4, 3-1=2段长度为3
        // 结论: 长度为L的链表, 分成k段, [a个"L/k向下取整", b个"L/k向上取整"]
        //       其中, a=L%k, b=k-b
        ListNode[] result = new ListNode[k];
        int L = 0;
        ListNode node = head;
        while (node != null) {
            L++;
            node = node.next;
        }
        int floor = L / k;
        int ceil = (int) Math.ceil((float) L / k);
        int a = L % k;
        int b = k - a;
        // split
        int i = 0;
        ListNode pre = null;
        ListNode newHead = head;
        node = head;
        for (int j = 0; j < a; j++) {
            for (int l = 0; l < ceil; l++) {
                pre = node;
                node = node.next;
            }
            if (pre != null) pre.next = null;
            else newHead = null;
            result[i++] = newHead;
            newHead = node;
        }
        for (int j = 0; j < b; j++) {
            for (int l = 0; l < floor; l++) {
                pre = node;
                node = node.next;
            }
            if (pre != null) pre.next = null;
            result[i++] = newHead;
            newHead = node;
        }
        return result;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/284946.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号