LeetCode 笔记系列六 Reverse Nodes in k-Group [学习如何逆转一个单链表]
题目:Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
这个题目花了蛮长时间,主要是没搞清楚逆转一个链表的关系。弄了半天。其实是蛮简单和经典的题目。
解法一:比较挫的解法。要判断很多分支,所以容易出错。先放在这里当反面教材。
public static ListNode reverseKGroup(ListNode head, int k) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode firstGHead = head;
int idx = 0;
ListNode pp = null;
while(head != null) {
ListNode c = head;
if(k <= 1 || c == null)return firstGHead;
for(int i = 0; i < k - 1&& c != null;i++) {
c = c.next;
}
if(c == null) break;
c = head;//save original head
int i = k - 1;
ListNode p = head;
ListNode pn = p.next;
ListNode lastEnd = pp;
while(i > 0){
p = head;
head = head.next;
pn = p.next;
pp = lastEnd;
int swap = 0;
while(swap < i){
p.next = pn.next;
pn.next = p;
if(pp != null)
pp.next = pn;
pp = pn;
pn= p.next;
swap++;
}
i--;
}
if(idx++ == 0) firstGHead = head;
head = c.next;
pp = c;
}
return firstGHead;
逆转那部分惨不忍睹啊。。。虽然过了leetcode,但是很不simple。还有,如果写成递归leetcode是不让你过的。
解法二:比较好的解法,又是leetcode讨论组的人做的。首先,搞清楚怎么逆转一个单链表。其实O(n)就可以了。第一个肯定是last one。然后我们每遍历到一个node,就把它放到最链表的首位,最后一个么,最后就成为第一个了。下面是一个简单逆转链表的程序。
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
ListNode cur = head.next;
ListNode last = head;
while(cur != null){
last.next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = last.next;
}
head = dummy.next;
reverse a linked list with a head node
因为有“放到链表首位”的操作,我们需要一个dummy的头节点,遇到的新节点我们simply state: pre.next = cur; 保持一个invariant就是last节点始终在最后(cur的前面一个)
然后我们有如下方法:
/**
* Reverse a link list between pre and next exclusively
* an example:
* a linked list:
* 0->1->2->3->4->5->6
* | |
* pre next
* after call pre = reverse(pre, next)
*
* 0->3->2->1->4->5->6
* | |
* pre next
* @param pre
* @param next
* @return the reversed list's last node, which is the precedence of parameter next
*/
private static ListNode reverse(ListNode pre, ListNode next){
ListNode last = pre.next;//where first will be doomed "last"
ListNode cur = last.next;
while(cur != next){
last.next = cur.next;
cur.next = pre.next;
pre.next = cur;
cur = last.next;
}
return last;
}
reverse range
就是区间的reverse。因为题目要求的是k group逆转嘛。注意人返回的是最后一个(last)节点,这样下一个k-group就可以用上了。牛人的想法真是周到体贴~~。主方法里面,遍历的过程中每次都计数,每次到达k个节点,就可以使用pre和head.next调用上面的方法逆转了。给跪了。
public static ListNode reverseKGroup2(ListNode head, int k) {
if(head == null || k == 1) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
int i = 0;
while(head != null){
i++;
if(i % k ==0){
pre = reverse(pre, head.next);
head = pre.next;
}else {
head = head.next;
}
}
return dummy.next;
}
reverseKGroup
通过这道题,我们学会了:
有效的算法是简洁的!简洁的!!简洁的!!!
LeetCode 笔记系列六 Reverse Nodes in k-Group [学习如何逆转一个单链表]的更多相关文章
- [Leetcode] Reverse nodes in k group 每k个一组反转链表
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If ...
- Reverse Nodes In K Group,将链表每k个元素为一组进行反转---特例Swap Nodes in Pairs,成对儿反转
问题描述:1->2->3->4,假设k=2进行反转,得到2->1->4->3:k=3进行反转,得到3->2->1->4 算法思想:基本操作就是链表 ...
- leetcode第24题--Reverse Nodes in k-Group
problem: Given a linked list, reverse the nodes of a linked list k at a time and return its modified ...
- sql server 关于表中只增标识问题 C# 实现自动化打开和关闭可执行文件(或 关闭停止与系统交互的可执行文件) ajaxfileupload插件上传图片功能,用MVC和aspx做后台各写了一个案例 将小写阿拉伯数字转换成大写的汉字, C# WinForm 中英文实现, 国际化实现的简单方法 ASP.NET Core 2 学习笔记(六)ASP.NET Core 2 学习笔记(三)
sql server 关于表中只增标识问题 由于我们系统时间用的过长,数据量大,设计是采用自增ID 我们插入数据的时候把ID也写进去,我们可以采用 关闭和开启自增标识 没有关闭的时候 ,提示一下错 ...
- LeetCode(25)Reverse Nodes in k-Group
题目 Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. ...
- LeetCode 笔记系列 18 Maximal Rectangle [学以致用]
题目: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones ...
- LeetCode 笔记系列16.3 Minimum Window Substring [从O(N*M), O(NlogM)到O(N),人生就是一场不停的战斗]
题目:Given a string S and a string T, find the minimum window in S which will contain all the characte ...
- LeetCode 笔记系列12 Trapping Rain Water [复杂的代码是错误的代码]
题目:Given n non-negative integers representing an elevation map where the width of each bar is 1, com ...
- LeetCode 笔记系列八 Longest Valid Parentheses [lich你又想多了]
题目:Given a string containing just the characters '(' and ')', find the length of the longest valid ( ...
随机推荐
- Exif.js 读取图像的元数据
Exif.js 提供了 JavaScript 读取图像的原始数据的功能扩展,例如:拍照方向.相机设备型号.拍摄时间.ISO 感光度.GPS 地理位置等数据. 注意事项: EXIF 数据主要来自拍摄的照 ...
- C#如何实现一个简单的流程图设计器
以前看过不少Window Form开发的流程图设计器,支持节点拖放,非常方便即可设计出很美观的流程图,作为一个程序员,对其内部实现原理一直很好奇,感叹有朝一日自己如果可以开发一款类似的软件那是多么让人 ...
- knockout源码分析之computed(依赖属性)
一.序列图 二.主要代码文件 1.dependentObservable.js:主要包含ko.computed相关方法的处理2.dependencyDetection.js:主要包含依赖的监控上下文对 ...
- jQuery Pjax – 页面无刷新加载,优化用户体验
pjax 是 HTML5 pushState 以及 Ajax 两项技术的简称,综合这两个技术可以实现在不刷新页面的情况下载入 HTML 到当前网页,带给你超快速的浏览器体验,而且有固定链接.标题以及后 ...
- [deviceone开发]-QQ分享、微信分享和新浪微博分享
一.简介 该demo主要实现QQ分享.微信分享和新浪微博分享.(调试包请到论坛扫描对应二维码下载) 二.效果图 三.相关讨论 http://bbs.deviceone.net/forum.php?mo ...
- JScript中的条件注释详解(转载自网络)
JScript中的条件注释详解-转载 这篇文章主要介绍了JScript中的条件注释详解,本文讲解了@cc_on.@if.@set.@_win32.@_win16.@_mac等条件注释语句及可用于条件编 ...
- SharePoint 2013 PowerShell命令备份还原报错
错误截图: 文字描述: Restore-SPSite : <nativehr>0x80070003</nativehr><nativestack></nati ...
- Mac下的Parallel Windows忘记密码怎么办?
Mac机上安装了Parallel Windows,日久年深不登录结果忘记了登录密码,百爪挠心,想破脑壳试了n个密码都不行,放了一个多月也没想起来. 今天没事网上溜溜,肯定也有和我同病相怜的弟兄,果然, ...
- Ioc Autofac心得
对于这个容器注入,个人也不是很熟悉,很多还不懂,只会基本的操作,几天把它记录下来,说不定以后帮助就大了呢,这方面跟安卓差距还是挺大的 下面记录下应用的流程 步骤: 1.添加应用 2.重写工厂(这里讲的 ...
- IOS常用第三方开源类库&组件
1.AFNetworking AFNetworking 采用 NSURLConnection + NSOperation, 主要方便与服务端 API 进行数据交换, 操作简单, 功能强大, 现在许多人 ...