Leetcode725

2018-11-14  本文已影响0人  zhouwaiqiang

题目

解题思路

源代码实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode[] splitListToParts(ListNode root, int k) {
        ListNode[] result = new ListNode[k];
        int count = 0;
        ListNode index = root;
        while (index != null) {
            count++;
            index = index.next;
        }
        int average = count/k;//平均的
        int remaining = count % k;//剩余的
        index = root;
        ListNode head = root;//每一段的头
        for (int i = 0; i < k; i++) {
            int total = i < remaining ? average + 1 : average;
            for (int j = 0; j < total - 1; j++) {   
                if (index != null) index = index.next;
            }
            result[i] = head;
            ListNode last = index;
            if (last != null) {
                index = index.next;
                head = index;
                last.next = null;
            } else head = null;
        }
        return result;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读