首页 > 代码库 > 86. Partition List

86. Partition List

  • Total Accepted: 89180
  • Total Submissions: 281459
  • Difficulty: Medium
  • Contributors: Admin

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

来源: https://leetcode.com/problems/partition-list/

分析


使用两个数组存储小于 x 和 不小于 x的数字,然后重新幅值给list
时间复杂度O(N), 空间复杂度O(N)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        /** we can use two vector<int> store different types of numbers, n1 record the number smaller than x, n2 record 
         *  the numbers no-smaller than x
         */
         if(head == NULL || head->next == NULL) return head;
          
         vector<int> n1, n2;
         ListNode* p = head;
         while(p != NULL){
             p->val < x ? n1.push_back(p->val) : n2.push_back(p->val);
             p = p->next;
         }
         p = head;
         for(auto n: n1){
             p->val = n;
             p = p->next;
         }
         for(auto n: n2){
             p->val = n;
             p = p->next;
         }
          
         return head;
         
    }
};

新建两个 node ,分别存储小于 和 不小于的数字,然后合并
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if(head == NULL || head->next == NULL) return head;
         
        ListNode dummy1(0), dummy2(0);
        ListNode* p1 = &dummy1, * p2 = &dummy2;
        while(head != NULL){
            // using reference to reduce the code lines
            ListNode* & ref = head->val < x ? p1 : p2;
            ref->next = head;
            ref = ref->next;
            /**
            if(head->val < x){
                p1->next = head;
                p1 = p1->next;
            }
            else{
                p2->next = head;
                p2 = p2->next;
            }
            */
            head = head->next;
        }
        p1->next = dummy2.next;
         
        // notice that this step makes sure that there is no loop in the new list
        p2->next = NULL;
        return dummy1.next;
    }
};


null


86. Partition List