-
Notifications
You must be signed in to change notification settings - Fork 96
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
第276题(2020-08-11):排序链表(腾讯&leetcode) #279
Comments
解答:采用归并排序归并排序采用了分治策略,将数组分成2个较小的数组,然后每个数组再分成两个更小的数组,直至每个数组里只包含一个元素,然后将小数组不断的合并成较大的数组,直至只剩下一个数组,就是排序完成后的数组序列。 对应于链表喃?
第一步:分割 使用快慢指针(双指针法),获取链表的中间节点 代码实现
引入递归算法的复杂度分析:
复杂度分析
关于复杂度分析,请看这篇:前端进阶算法1:如何分析、统计算法的执行效率和资源消耗? |
我来提供一个插入排序的实现 type LinkListNode<T> = {
value: T;
next: LinkListNode<T> | null;
}
// 递归
function insertSortRecursive<T>(head: LinkListNode<T>): LinkListNode<T> {
return head.next ? insert(head, insertSort(head.next)) : head
}
// 循环
function insertSort<T>(head: LinkListNode<T>): LinkListNode<T> {
let tail = head.next
head.next = null
let sorted = head
while (tail) {
const tempNode = tail;
tail = tail.next;
sorted = insert(tempNode, sorted)
}
return sorted
}
function insert<T>(node: LinkListNode<T>, head: LinkListNode<T>): LinkListNode<T> {
let temp: LinkListNode<T> | null = head
let parentTemp: LinkListNode<T> | null = null
while (temp && temp.value < node.value) {
parentTemp = temp
temp = temp.next
}
if (parentTemp) {
parentTemp.next = node
node.next = temp
return head
} else {
node.next = head
return node
}
} 测试如下 function printLinkList<T>(head: LinkListNode<T>) {
let temp = head
let count = 1;
while (temp) {
console.log(`[${count++}] `, temp.value)
temp = temp.next
}
}
function test() {
const rand = () => Math.floor(Math.random() * 1000)
let node: LinkListNode<number> = {
value: rand(),
next: null
}
let temp = node;
for (let i = 1; i < 10; ++i) {
temp.next = { value: rand(), next: null}
temp = temp.next
}
printLinkList(node)
console.log("===== Sorted =====")
printLinkList(insertSort(node))
}
test();
/**
[1] 620
[2] 191
[3] 581
[4] 285
[5] 141
[6] 140
[7] 822
[8] 405
[9] 788
[10] 208
===== Sorted =====
[1] 140
[2] 141
[3] 191
[4] 208
[5] 285
[6] 405
[7] 581
[8] 620
[9] 788
[10] 822
*/ |
复杂度分析: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: