当前位置:网站首页>2022.07.18 _ a day
2022.07.18 _ a day
2022-07-31 07:40:00 【No. い】
147. 对链表进行插入排序
题目描述
给定单个链表的头 head ,使用 插入排序 对链表进行排序,并返回 排序后链表的头 .
插入排序 算法的步骤:
- 插入排序是迭代的,每次只移动一个元素,直到所有元素可以形成一个有序的输出列表.
- 每次迭代中,插入排序只从输入数据中移除一个待排序的元素,找到它在序列中适当的位置,并将其插入.
- 重复直到所有输入数据插入完为止.
下面是插入排序算法的一个图形示例.部分排序的列表(黑色)最初只包含列表中的第一个元素.每次迭代时,从输入数据中删除一个元素(红色),并就地插入已排序的列表中.
对链表进行插入排序.

示例 1:

输入: head = [4,2,1,3] 输出: [1,2,3,4]
示例 2:

输入: head = [-1,5,3,4,0] 输出: [-1,0,3,4,5]
提示:
- 列表中的节点数在
[1, 5000]范围内 -5000 <= Node.val <= 5000
- 链表
- 排序
coding
1. Insertion sort on linked list directly
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode node1 = head.next;
while (node1 != null) {
ListNode node2 = head;
while (node1 != node2) {
if (node2.val > node1.val) {
int temp = node2.val;
node2.val = node1.val;
node1.val = temp;
}
node2 = node2.next;
}
node1 = node1.next;
}
return head;
}
}
2. 将链表转换为数组,直接调用 Arrays.sort();
class Solution {
public ListNode insertionSortList(ListNode head) {
ListNode node = head;
int cnt = 0;
while (node != null) {
node = node.next;
cnt ++;
}
node = head;
int[] arr = new int[cnt];
while (node != null) {
arr[--cnt] = node.val;
node = node.next;
}
Arrays.sort(arr);
node = head;
for (int i : arr) {
node.val = i;
node = node.next;
}
return head;
}
}
边栏推荐
- 【Star项目】小帽飞机大战(七)
- 04-SDRAM: Read Operation (Burst)
- Zabbix6.2惊喜发布!特别优化中大型环境部署的性能!
- Postgresql source code learning (33) - transaction log ⑨ - see the overall process of log writing from the insert record
- 04-SDRAM:读操作(突发)
- 剑指offer(一)
- postgresql源码学习(33)—— 事务日志⑨ - 从insert记录看日志写入整体流程
- Core Tower Electronics won the championship in the Wuhu Division of the 11th China Innovation and Entrepreneurship Competition
- 2022.07.15_每日一题
- 2022.07.18_每日一题
猜你喜欢

文件 - 04 下载文件: 根据文件下载链接下载文件

【TA-霜狼_may-《百人计划》】美术2.3 硬表面基础

解决安装 Bun 之后出现 zsh compinit: insecure directories, run compaudit for list. Ignore insecure directorie

关于求反三角函数的三角函数值

2. (1) Chained storage of stack, operation of chain stack (illustration, comment, code)

【解决】npm ERR A complete log of this run can be found in npm ERR

Analysis of the principle and implementation of waterfall flow layout

毫米波技术基础

Some derivation formulas for machine learning backpropagation

iOS大厂面试查漏补缺
随机推荐
科普 | “大姨太”ETH 和 “小姨太”ETC的爱恨情仇
One of the small practical projects - food alliance ordering system
2022.7.29 数组
Jobject 使用
CHI论文阅读(1)EmoGlass: an End-to-End AI-Enabled Wearable Platform for Enhancing Self-Awareness of Emoti
简单谈谈Feign
postgresql源码学习(34)—— 事务日志⑩ - 全页写机制
基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例
把 VS Code 当游戏机
电压源的电路分析知识分享
2022.07.15_每日一题
外贸网站优化-外贸网站优化教程-外贸网站优化软件
电脑开机密码怎么设置?如何给你的电脑加上“安全锁”
van-uploader上传图片,使用base64回显无法预览的问题
MySQL笔记下
【Go语言入门】一文搞懂Go语言的最新依赖管理:go mod的使用
iOS大厂面试查漏补缺
Log4net 思维导图
2022.07.26_每日一题
SQL Server Datetime2数据类型