【LeetCode】147. Insertion Sort List 对链表进行插入排序(Medium)(JAVA)
题目地址: https://leetcode.com/problems/insertion-sort-list/
题目描述:
Sort a linked list using insertion sort.
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
Algorithm of Insertion Sort:
- Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
- At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
- It repeats until no input elements remain.
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
题目大意
对链表进行插入排序。
插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。
插入排序算法:
- 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
- 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
- 重复直到所有输入数据插入完为止。
解题方法
- 根据采用插入排序的方法,对链表进行排序
- 插入排序:找到 A 节点,A.val < cur.val <= A.next.val,然后插入在 A 节点后面即可
- 不断循环往排序过的链表里插入节点即可
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode res = null;
while (head != null) {
ListNode cur = head;
head = head.next;
cur.next = null;
res = insert(res, cur);
}
return res;
}
public ListNode insert(ListNode head, ListNode ins) {
if (head == null) return ins;
if (head.val >= ins.val) {
ins.next = head;
return ins;
}
ListNode res = head;
while (head != null && head.next != null && head.next.val < ins.val) {
head = head.next;
}
ListNode next = head.next;
head.next = ins;
ins.next = next;
return res;
}
}
执行耗时:22 ms,击败了38.50% 的Java用户
内存消耗:38.2 MB,击败了72.52% 的Java用户