当前位置:网站首页>鏈錶內指定區間反轉
鏈錶內指定區間反轉
2022-07-03 01:01:00 【Schuyler Hu】
問題
將一個節點數為 size 鏈錶 m 比特置到 n 比特置之間的區間反轉,要求時間複雜度 O(n),空間複雜度 O(1)。
思路
- 采用雙指針移動到指定比特置: pre 移動到挪動區間的起始比特置的前一個比特置,cur 移動到挪動區間的起始比特置。
- 連接 cur 與 cur 的下下個元素,斷開 cur 與 next 的連接;next 連接到 pre 後一元素之前;pre 指向 next。
代碼實現
/** * struct ListNode { * int val; * struct ListNode *next; * }; */
class Solution {
public:
/** * * @param head ListNode類 * @param m int整型 * @param n int整型 * @return ListNode類 */
ListNode* reverseBetween(ListNode* head, int m, int n) {
// write code here
ListNode* dummyHead = new ListNode(0);
dummyHead->next = head;
ListNode* pre = dummyHead;
// 0 < m < size,所以本題鏈錶下標從 1 開始,pre 指向翻轉區間的起始前一個比特置
for (int i = 1; i < m; i++)
{
pre = pre->next;
}
ListNode* cur = pre->next;
for (int i = m; i < n; i++)
{
ListNode* next = cur->next;
// 斷開 cur 與 next 的連接
cur->next = next->next;
// 將後續的 next 移動到 pre 下一個元素前
next->next = pre->next;
// 連接 pre 和 next
pre->next = next;
}
return dummyHead->next;
}
};
边栏推荐
- The difference between relational database and non relational database
- 世平信息首席科学家吕喆:构建以数据和人员为中心的安全能力
- File operation io-part2
- 研发一款国产ARM智能边缘计算网关需要什么
- 链表中的节点每k个一组翻转
- 飞凌搭载TI AM62x的ARM核心板/开发板首发上市,亮相Embedded World 2022
- [shutter] image component (cached_network_image network image caching plug-in)
- FPGA - 7系列 FPGA内部结构之Clocking -04- 多区域时钟
- Leetcode-871: minimum refueling times
- 【AutoSAR 七 工具链简介】
猜你喜欢
深度剖析数据在内存中的存储
The difference between tail -f, tail -f and tail
kubernetes资源对象介绍及常用命令(五)-(NFS&PV&PVC)
Use Jenkins II job
Shell implements basic file operations (cutting, sorting, and de duplication)
百度智能云牵头打造智能云综合标准化平台
[AUTOSAR + IO Architecture]
Arduino开发之按键检测与正弦信号输出
Web2.0 giants have deployed VC, and tiger Dao VC may become a shortcut to Web3
[flutter] icons component (load the built-in icon of flutter | display the material design icon completely)
随机推荐
2022上半年值得被看见的10条文案,每一句都能带给你力量!
leetcode-1964:找出到每个位置为止最长的有效障碍赛跑路线
Understanding and distinguishing of some noun concepts in adjustment / filtering
【AutoSAR 七 工具链简介】
leetcode-2115:从给定原材料中找到所有可以做出的菜
1.12 - Instructions
如何系统学习机器学习
Vulkan-性能及精细化
[AUTOSAR II appl overview]
leetcode-241:为运算表达式设计优先级
【AutoSAR 十二 模式管理】
matlab将数字矩阵保存为地理空间数据出错,显示下标索引必须为正整数类型或逻辑类型,解决
【AutoSAR 四 BSW概述】
Solve the cache problem of reactnative using WebView
Leetcode-934: the shortest Bridge
文件操作IO-Part2
Test shift right: Elk practice of online quality monitoring
Tensorflow 2.x(keras)源码详解之第十五章:迁移学习与微调
The difference between tail -f, tail -f and tail
【AutoSAR 八 OS】