Skip to content

[LeetCode] 725. 分隔链表 #97

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Animenzzzz opened this issue Sep 22, 2019 · 0 comments
Open

[LeetCode] 725. 分隔链表 #97

Animenzzzz opened this issue Sep 22, 2019 · 0 comments

Comments

@Animenzzzz
Copy link
Owner

题目描述:

给定一个头结点为 root 的链表, 编写一个函数以将链表分隔为 k 个连续的部分。

每部分的长度应该尽可能的相等: 任意两部分的长度差距不能超过 1,也就是说可能有些部分为 null。

这k个部分应该按照在链表中出现的顺序进行输出,并且排在前面的部分的长度应该大于或等于后面的长度。

返回一个符合上述规则的链表的列表。

举例: 1->2->3->4, k = 5 // 5 结果 [ [1], [2], [3], [4], null ]

示例 1:

输入: 
root = [1, 2, 3], k = 5
输出: [[1],[2],[3],[],[]]
解释:
输入输出各部分都应该是链表,而不是数组。
例如, 输入的结点 root 的 val= 1, root.next.val = 2, \root.next.next.val = 3, 且 root.next.next.next = null。
第一个输出 output[0] 是 output[0].val = 1, output[0].next = null。
最后一个元素 output[4] 为 null, 它代表了最后一个部分为空链表。

示例 2:

输入: 
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
输出: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
解释:
输入被分成了几个连续的部分,并且每部分的长度相差不超过1.前面部分的长度大于等于后面部分的长度。

提示:

root 的长度范围: [0, 1000].
输入的每个节点的大小范围:[0, 999].
k 的取值范围: [1, 50].

解题思路:首先计算链表的长度,然后num=list_size/k算出每条链的长度,求余yu,给yu条链加上1的长度。一次循环num次,加上yu的1个,则为一整条链,最后记得将每条链的 末尾->next 置空,避免连起来。

C++解题:

class Solution {
public:
    vector<ListNode*> splitListToParts(ListNode* root, int k) {
        int list_size = 0,num = 0,yu = 0;
        vector<ListNode*> res;
        ListNode* tmp = root;
        while(tmp){
            list_size++;
            tmp = tmp->next;
        }
        num = list_size/k;
        yu = list_size%k;
        tmp = root;
        while (k)
        {
            res.push_back(tmp);
            ListNode* tmp_pre;
            for (int i = 0; i < num; i++){
                tmp_pre = tmp;
                tmp = tmp->next;
            } 
            if(yu){
                yu--;
                tmp_pre = tmp;
                tmp = tmp->next;
            }
            tmp_pre->next = NULL;
            k--;
        }
        return res;
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant