leetcode 725. Split Linked List in Parts | 725. 分隔链表(Java)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 725. Split Linked List in Parts | 725. 分隔链表(Java)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目
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.
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/ class Solution {public ListNode[] splitListToParts(ListNode head, int k) {// 例1: 長(zhǎng)度為10的鏈表, 分成3段, [4 3 3]// 其中,10%3=1段長(zhǎng)度為4, 3-1=2段長(zhǎng)度為3// 例2: 長(zhǎng)度為11的鏈表, 分成3段, [4 4 3]// 其中,11%3=2段長(zhǎng)度為4, 3-1=2段長(zhǎng)度為3// 結(jié)論: 長(zhǎng)度為L(zhǎng)的鏈表, 分成k段, [a個(gè)"L/k向下取整", b個(gè)"L/k向上取整"]// 其中, a=L%k, b=k-bListNode[] 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;// splitint 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;} }總結(jié)
以上是生活随笔為你收集整理的leetcode 725. Split Linked List in Parts | 725. 分隔链表(Java)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: leetcode 214. Shorte
- 下一篇: leetcode 547. Number