Sort List ——LeetCode】的更多相关文章

这个题一开始本想用快速排序的,但是想了20分钟都没有头绪,难点在于快速排序的随机访问无法用链表实现,不过如果可以实现快速排序partition函数就可以了,但是这可能比较复杂,于是改用其他排序方法,上网查了下,大部分都采用了归并排序,归并排序并不需要有跨度的访问元素,可能唯一耗时的就是寻找中间点,这个可以利用两个指针,一个指针是另一个指针移动速度两倍来找到中间节点. 首先采用自顶向下的递归方法实现: // Definition for singly-linked list. struct Lis…
用python实现多级排序,可以像C语言那样写个my_cmp,然后在sort的时候赋给参数cmp即可 但实际上,python处理cmp 是很慢的,因为每次比较都会调用my_cmp:而使用key和reverse就快得多,因为只需要在排序开始时处理一次即可,因此在排序的时候能不用cmp就尽量不用 另外可以用operator函数中的itemgetter,和attrgetter实现基于key的(多级)排序: from operator import itemgetter, attrgetter sort…
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…
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. 链表排序,要求时间复杂度O(nlgn),我写的归并排序. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solu…
Sort a linked list using insertion sort. 题目大意:将一个单链表使用插入排序的方式排序. 解题思路:先新建一个头指针,然后重新构建一下这个单链表,每次从头找到第一个比当前元素大的,插在这个元素前面. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * }…
179. Largest Number sort(num.begin(), num.end(), [](int a, int b){ return to_string(a)+to_string(b) > to_string(b)+to_string(a); } );…
Sort a linked list using insertion sort. 这个题我巧妙的设置了一个临时头结点 class Solution { public: ListNode* insertionSortList(ListNode* head) { if (head == nullptr) return head; ListNode temp(); temp.next = head; head = &temp; ListNode *cur = head->next; while (…
题目: 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, an…
题目: Sort a linked list in O(n log n) time using constant space complexity. 题解: 考虑到要求用O(nlogn)的时间复杂度和constant space complexity来sort list,自然而然想到了merge sort方法.同时我们还已经做过了merge k sorted list和merge 2 sorted list.这样这个问题就比较容易了. 不过这道题要找linkedlist中点,那当然就要用最经典的…