Only one time scan, 2 level pointer, inplace change, hack break from inner loop, all in one!!!


  • 0
    0
    class Solution {
    public:
        vector<ListNode*> splitListToParts(ListNode* root, int k) {
            vector<ListNode**> pps(k, &root);
            [&pps]() {
                while (*pps.back()) {
                    for (int i = 0; i < (int)pps.size(); ++i) {
                        for (int p = i; p < (int)pps.size(); ++p) {
                            if (*pps[p]) pps[p] = &(*pps[p])->next;
                            if (!*pps.back()) return;
                        }
                    }
                }
            }();
            vector<ListNode*> res {root};
            for (ListNode** pp : pps) {
                res.push_back(*pp);
                *pp = nullptr;
            }
            res.pop_back();
            return res;
        }
    };

Log in to reply
 

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