当前位置:网站首页>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;
}
}
边栏推荐
- 基于交替迭代法的交直流混合系统潮流计算matlab程序iEEE9节点系统算例
- 【并发编程】ReentrantLock的lock()方法源码分析
- Analysis of the implementation principle and detailed knowledge of v-model syntactic sugar and how to make the components you develop support v-model
- [PSQL] SQL基础教程读书笔记(Chapter1-4)
- 2022.07.24_每日一题
- Detailed explanation of js prototype
- 从 Google 离职,前Go 语言负责人跳槽小公司
- MySQL笔记下
- 高并发与多线程之间的难点对比(容易混淆)
- 文件 - 07 删除文件: 根据fileIds批量删除文件及文件信息
猜你喜欢

Run the NPM will pop up to ask "how are you going to open this file?"

简单谈谈Feign

零样本学习&Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning

【Go报错】go go.mod file not found in current directory or any parent directory 错误解决

Foreign trade website optimization - foreign trade website optimization tutorial - foreign trade website optimization software

LeetCode刷题——摆动序列#376#Medium

电脑开机密码怎么设置?如何给你的电脑加上“安全锁”

LeetCode:952. 按公因数计算最大组件大小【欧拉筛 + 并查集】

Zero-Shot Learning & Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning

DirectExchange switch simple introduction demo
随机推荐
2022.07.15_每日一题
关于求反三角函数的三角函数值
[PSQL] SQL基础教程读书笔记(Chapter1-4)
tidyverse笔记——管道函数
什么是半波整流器?半波整流器的使用方法
【科普向】5G核心网架构和关键技术
SCI写作指南
文件 - 02 上传文件:上传临时文件到服务器
Exam Questions Previous True Questions Wrong Bills [The Fourth Session] [Provincial Competition] [Group B]
零样本学习&Domain-aware Visual Bias Eliminating for Generalized Zero-Shot Learning
一文读懂 MongoDB 和 MySQL 的差异
【 TA - frost Wolf _may - "one hundred plan" 】 art 2.3 hard surface
R——避免使用 col=0
【Star项目】小帽飞机大战(八)
LeetCode:952. 按公因数计算最大组件大小【欧拉筛 + 并查集】
Log4net 思维导图
2022.07.22_每日一题
基于LSTM的诗词生成
强化学习科研知识必备(数据库、期刊、会议、牛人)
批量翻译软件免费【2022最新版】