【LeetCode】147. Insertion Sort List 对链表进行插入排序(Medium)(JAVA)每日一题

【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:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
  2. 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.
  3. 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

题目大意

对链表进行插入排序。

插入排序的动画演示如上。从第一个元素开始,该链表可以被认为已经部分排序(用黑色表示)。
每次迭代时,从输入数据中移除一个元素(用红色表示),并原地将其插入到已排好序的链表中。

插入排序算法:

  1. 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表。
  2. 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入。
  3. 重复直到所有输入数据插入完为止。

解题方法

  1. 根据采用插入排序的方法,对链表进行排序
  2. 插入排序:找到 A 节点,A.val < cur.val <= A.next.val,然后插入在 A 节点后面即可
  3. 不断循环往排序过的链表里插入节点即可
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用户

欢迎关注我的公众号,LeetCode 每日一题更新
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值