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

LeetCode--Sort List Question Sort a linked list in O(n log n) time using constant space complexity. Solution 看到对链表的排序,时间复杂度O(n log n),首先想到的就是归并排序. 但是这里其中有两个技巧: 就是将两个链表分开的时候,用到了fast-slow法,这是在处理链表分治,也就是找中间节点的一种有效方法. 还有就是merge的过程,也用到了递归的方式. Code /** * D…
Given a string, sort it in decreasing order based on the frequency of characters. Example 1: Input: "tree" Output: "eert" Explanation: 'e' appears twice while 'r' and 't' both appear once. So 'e' must appear before both 'r' and 't'. Th…
Sort a linked list in O(n log n) time using constant space complexity. 常见排序方法有很多,插入排序,选择排序,堆排序,快速排序,冒泡排序,归并排序,桶排序等等..它们的时间复杂度不尽相同,而这里题目限定了时间必须为O(nlgn),符合要求只有快速排序,归并排序,堆排序,而根据单链表的特点,最适于用归并排序.代码如下: C++ 解法一: class Solution { public: ListNode* sortList(L…
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…
原题地址:https://oj.leetcode.com/problems/sort-colors/ 题意: 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 integer…
Sort List Sort a linked list in O(n log n) time using constant space complexity. 使用Merge Sort, 空间复杂度是 O(logN) 因为使用了栈空间. SOLUTION 1: 使用Merge Sort来解决问题. 为什么不用QuickSort? 因为随机访问对于链表而言太耗时,而heap sort不可行. 注意,Find Mid用了2种解法.或者是让Fast提前结束,或是让Fast先走一步,目的就是要取得中间…
Status: AcceptedRuntime: 66 ms 题意:根据给出的单链表,用O(nlogn)的时间复杂度来排序.由时间复杂度想到快排.归并这两种排序.本次用的是归并排序.递归将链表的规模不断二分到只剩下1或2个元素为止,这也是递归出口,一旦出现这两种情况就可以返回.这里有个问题,链表也能二分?可以的,只是麻烦了些,用两个指针可以实现找到中点.本次代码没有详细分析具体的复杂度,但确实是归并. 注意:要考虑空链表,单个元素的链表,以及多个元素的链表. LeetCode的代码: /** *…
Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f(x) = ax2 + bx + c to each element x in the array. The returned array must be in sorted order. Expected time complexity: O(n) Example: nums = [-4, -2,…
Given a sorted array of integers nums and integer values a, b and c. Apply a function of the form f(x) = ax2 + bx + c to each element x in the array. The returned array must be in sorted order. Expected time complexity: O(n) Example: nums = [-4, -2,…
Sort a linked list in O(n log n) time using constant space complexity. /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *sort…