LeetCode148 排序鍊錶

2021-09-26 20:18:41 字數 1651 閱讀 5859

在 o(n log n) 時間複雜度和常數級空間複雜度下,對鍊錶進行排序。

示例 1:

輸入: 4->2->1->3

輸出: 1->2->3->4

示例 2:

輸入: -1->5->3->4->0

輸出: -1->0->3->4->5

原題鏈結;

方法一:笨方法

利用附加的陣列記住鍊錶的值,再對陣列排序,再輸出鍊錶。

/**

* definition for singly-linked list.

* public class listnode

* }*/class solution

int heap = new int[count];

int size = 0;

while(head!=null)

arrays.sort(heap);

listnode ans = new listnode(0);

listnode nownode = ans;

for(int i = 0; io(n)

空間複雜度,不滿足題目要求。

方法二:歸併排序

自己寫的歸併排序:

class solution 

public listnode divide(listnode head )

listnode fast = head.next;

listnode slow = head;

while(fast != null)

listnode right = slow.next;

slow.next = null;

headcopy = divide(headcopy);

right = divide(right);

headcopy = merge(headcopy, right);

return headcopy;

}public listnode merge(listnode left, listnode right)

else

}anscopy.next = left== null? right: left;

return ans.next;

}

}

Leetcode 148 排序鍊錶

在 o n log n 時間複雜度和常數級空間複雜度下,對鍊錶進行排序。示例 1 輸入 4 2 1 3 輸出 1 2 3 4示例 2 輸入 1 5 3 4 0 輸出 1 0 3 4 5在陣列儲存下的歸併排序,需要借出輔助空間完成,而鍊錶儲存的歸併排序,不需要借助輔助空間,直接在原來的鍊錶上進行操作,...

LeetCode 148 排序鍊錶

在 o n log n 時間複雜度和常數級空間複雜度下,對鍊錶進行排序。示例 1 輸入 4 2 1 3輸出 1 2 3 4示例 2 輸入 1 5 3 4 0輸出 1 0 3 4 5歸併這裡我感覺有點不符合題意 不符合常數空間 如果是快排的話呢,交換節點還是很麻煩的,所以快排交換值了 癱.jpg cl...

leetcode148 排序鍊錶

在 o n log n 時間複雜度和常數級空間複雜度下,對鍊錶進行排序。示例 1 輸入 4 2 1 3 輸出 1 2 3 4 示例 2 輸入 1 5 3 4 0 輸出 1 0 3 4 5 看到題目就知道要二分,這裡用的是遞迴版歸併 definition for singly linked list....