LeetCode 题解(140): Sort List

题目:

Sort a linked list in O(n log n) time using constant space complexity.

题解:

短短一行题目,Medium难度,让人写的欲仙欲死。

总体思想是in-place的Merge sort,只能有O(1)的空间复杂度。

每次Merge相邻的K个节点,K = 1, 2, 4, .....

记录每个pass merge的次数, 如只发生一次merge,表示排序完成,返回头指针。

内部子函数是在Merge two sorted linked list的基础上改的,也是O(1)space算法。

保证第二次写也不能短时间写出正确代码的强数据结构操作题

C++版:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
	ListNode* sortList(ListNode* head) {
		if(head == NULL)
		    return NULL;
		
		ListNode *newHead = NULL;
		int i = 0;
		int k = pow(2, i);
		ListNode *p = head;
		
		while (true) {
			int pass = 0;
			newHead = mergeTwoSortedLists(p, k, pass);
			if (pass == 1)
				break;
			k = pow(2, ++i);
			p = newHead;
		}
		return newHead;
	}

	ListNode* mergeTwoSortedLists(ListNode* p, int k, int& pass) {
		if (p == NULL)
			return NULL;
		
		pass++;
		int i = 0;
		ListNode* q = p;
		while (i < k && q != NULL) {
			q = q->next;
			i++;
		}

		if (q == NULL)
			return p;
		
		ListNode* head = NULL;
		if (p->val <= q->val)
			head = p;
		else
			head = q;

		int count1 = 0, count2 = 0;
		while (count1 < k && count2 < k && q != NULL) {
			while (p->val <= q->val && count1 + 1 < k && p->next->val <= q->val) {
				p = p->next;
				count1++;
			}
			if (p->val <= q->val) {
				ListNode* temp = p->next;
				p->next = q;
				p = temp;
				count1++;
			}
			if (count1 == k) {
				while (count2 + 1 < k && q->next != NULL) {
					q = q->next;
					count2++;
				}
				q->next = mergeTwoSortedLists(q->next, k, pass);
				break;
			}
			while (q->val < p->val && count2 + 1 < k && q->next != NULL && q->next->val < p->val) {
				q = q->next;
				count2++;
			}
			if (q->val < p->val) {
				ListNode* temp = q->next;
				q->next = p;
				q = temp;
				count2++;
			}
			if (count2 == k || q == NULL) {
				while (count1  + 1 < k) {
					p = p->next;
					count1++;
				}
				p->next = mergeTwoSortedLists(q, k, pass);
				break;
			}
		}
		return head;
	}
};



©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页