zoukankan      html  css  js  c++  java
  • 725. Split Linked List in Parts

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

    k>=length, 每个部分有且仅有一个,剩下k-length个部分都是空

    Input: 
    root = [1, 2, 3], k = 5
    Output: [[1],[2],[3],[],[]]

    k<length,每个部分至少有length/k个,那么剩下的length%k个就要给每个部分匀一个

    Input: 
    root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
    Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]

    最终有:

    前length%k个部分,size为(length/k)+1

    剩下的部分size就是length/k

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     public ListNode[] splitListToParts(ListNode root, int k) {
    11         ListNode[] result = new ListNode[k];
    12         int length = 0;
    13         for (ListNode cursor = root; cursor != null; cursor = cursor.next) {
    14             length++;
    15         }
    16         int perPartNum = length / k;
    17         int remainNum = length % k;
    18         ListNode head = root;
    19         ListNode perPartTail = null;
    20         for(int i = 0; i < k; i++, remainNum--){
    21             result[i] = head;
    22             for(int j = 0; j<perPartNum+(remainNum> 0 ? 1 : 0); j++){
    23                 perPartTail = head;
    24                 head = head.next;
    25             }
    26             if(perPartTail != null){
    27                 perPartTail.next = null;
    28             }
    29         }
    30         return result;
    31     }
    32 }
    remainNum就是需要匀出去的部分,最开始的几个在分配的时候就会多一个
  • 相关阅读:
    06-图3 六度空间 (30 分)
    06-图2 Saving James Bond
    06-图1 列出连通集 (25 分)
    05-树9 Huffman Codes (30 分)
    05-树8 File Transfer (25 分)
    05-树7 堆中的路径 (25 分)
    04-树6 Complete Binary Search Tree (30 分)
    04-树5 Root of AVL Tree (25 分)
    03-树3 Tree Traversals Again (25 分)
    只允许输入数字的TextBox控件
  • 原文地址:https://www.cnblogs.com/TheLaughingMan/p/10155128.html
Copyright © 2011-2022 走看看