Status: AcceptedRuntime: 66 ms 题意:根据给出的单链表,用O(nlogn)的时间复杂度来排序.由时间复杂度想到快排.归并这两种排序.本次用的是归并排序.递归将链表的规模不断二分到只剩下1或2个元素为止,这也是递归出口,一旦出现这两种情况就可以返回.这里有个问题,链表也能二分?可以的,只是麻烦了些,用两个指针可以实现找到中点.本次代码没有详细分析具体的复杂度,但确实是归并. 注意:要考虑空链表,单个元素的链表,以及多个元素的链表. LeetCode的代码: /** *…
Sort a linked list in O(n log n) time using constant space complexity. 常见排序方法有很多,插入排序,选择排序,堆排序,快速排序,冒泡排序,归并排序,桶排序等等..它们的时间复杂度不尽相同,而这里题目限定了时间必须为O(nlgn),符合要求只有快速排序,归并排序,堆排序,而根据单链表的特点,最适于用归并排序.代码如下: C++ 解法一: class Solution { public: ListNode* sortList(L…
Sort a linked list in O(n log n) time using constant space complexity. Example 1: Input: 4->2->1->3 Output: 1->2->3->4 Example 2: Input: -1->5->3->4->0 Output: -1->0->3->4->5 常见排序方法有很多,插入排序,选择排序,堆排序,快速排序,冒泡排序,归并排序…
插入排序的基本思想 把排好的放在一个新的变量中,每次拿出新的,排进去 这个新的变量要有超前节点,因为第一个节点可能会有变动 public ListNode insertionSortList(ListNode head) { if (head==null||head.next==null) return head; ListNode dummy = new ListNode(0); ListNode h = head; ListNode next; ListNode temp; while (h…
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and bl…
Sort a linked list in O(n log n) time using constant space complexity. Have you met this question in a real interview? Yes Example Given 1->3->2->null, sort it to 1->2->3->null. Challenge Solve it by merge sort & quick sort separatel…
Sort a linked list in O(n log n) time using constant space complexity. 这道题目非常简短的一句话.给链表排序,看到nlogn.我们能够来简单复习一下排序. 首先说一下这个nlogn的时间复杂度(依据决策树我们能够得出这个界限).是基于比較排序的最小上限,也就是说.对于没有一定范围情况的数据来说.最快的排序思路就是归并和高速排序了(当然详细的參数系数还是由更详细的设置决定的).对于数组的话,假设使用归并排序,不是in place…
STL 中 sort 函数用法简介 做 ACM 题的时候,排序是一种经常要用到的操作.如果每次都自己写个冒泡之类的 O(n^2) 排序,不但程序容易超时,而且浪费宝贵的比赛时间,还很有可能写错. STL 里面有个 sort 函数,可以直接对数组排序,复杂度为 n*log2(n) . 使用这个函数,需要包含头文件#include <algorithm>. 这个函数可以传两个参数或三个参数.第一个参数是要排序的区间首地址,第二个参数是区间尾地址的下一地址.也就是说,排序的区间是 [a,b) .简单…
题目:Sort List Sort a linked list in O(n log n) time using constant space complexity 看题目有两个要求:1)时间复杂度为O(nlogn);2)空间复杂度为常数,即不能增设额外的空间.满足这样要求的排序算法,我们首先想到快排,合并排序和堆排序.我们来分析下几种排序算法对时间和空间复杂度的要求,堆排序实现上过于繁琐,我们不做考虑.快排的最坏的时间复杂度是O(n^2),平均复杂度为O(nlgn),如果按照题目的严格要求显然…
题目:Sort a linked list in O(n log n) time using constant space complexity. 分析:给单链表排序,要求时间复杂度是O(nlogn),空间复杂度是O(1).时间复杂度为O(nlogn)的排序算法有快速排序和归并排序, 但是,对于单链表来说,进行元素之间的交换比较复杂,但是连接两个有序链表相对简单,因此这里采用归并排序的思路. 编码: public ListNode sortList(ListNode head) { if(hea…