Concise Java using Map


  • 0
    class Solution {
        public ListNode[] splitListToParts(ListNode root, int k) {
            Map<Integer, ListNode> map = new HashMap<>();
            int count = 0;
            while (root != null) {
                map.put(count, root);
                root = root.next;
                count++;
            }
    
            ListNode[] res = new ListNode[k];
            if (k > count) {
                while (k > count) {
                    res[k - 1] = null;
                    k--;
                }
            }
            while (k > 0) {
                int index = count - count / k;
                map.get(index + count / k - 1).next = null;
                res[k - 1] = map.get(index);
                
                count -= count / k;
                k--;
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.