LeetCode 笔记系列四 Remove Nth Node From End of List
题目:Given a linked list, remove the nth node from the end of list and return its head.For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
就是让你删除单链表倒数第n个节点,同时希望能只遍历一次。
解法一: 如果不遍历完所有节点,怎么知道倒数第n个在哪里呢?但是遍历完成以后,删除不是又需要遍历么?不过删除一个node实际上只需要一个pre node就行了。于是,考虑使用一个HashMap保存遍历过的节点,实现删除。
public ListNode removeNthFromEnd(ListNode head, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null) return null;
HashMap<Integer, ListNode> map = new HashMap<Integer, ListNode>();
int i = 0;
ListNode p = head;
while(p != null){
map.put(++i, p);
p = p.next;
}
ListNode pre = map.get(i - n);//i - n is the node that right BEFORE the to-be-deleted node.
if(pre != null){
ListNode deleted = pre.next;
if(deleted != null)
pre.next = deleted.next;
}else {//if pre is null, means we are deleting head
head = head.next;
}
return head;
}
HashSet deletion
感觉每次做题,如果用到了额外的数据结构或者空间,都有一种开挂的感觉。能不能不显式使用额外的空间或者数据结构呢?想到最近看了Algorithm 4th edtion关于递归删除BST的方法,有一些启发。
解法二: 我们尝试使用递归来解。
public ListNode removeNthFromEnd2(ListNode head, int n) {
if(head == null) return null;
int[] counter = new int[]{0};
return removeNthFromEnd2(head,n,counter);
}
private static ListNode removeNthFromEnd2(ListNode head, int n, int[] counter){
if(head.next == null){// we reached tail
counter[0] = 1;
}else {
head.next = removeNthFromEnd2(head.next, n, counter);
counter[0]++;//we increment this counter to record when we back from the recursive, namely back from the last node
}
if(counter[0] == n){//oh, this is nth node backward, we just RETURN THE NEXT NODE.
return head.next;
}else return head;//otherwise return whatever we received
}
recursive deletion
是不是看上去很简洁?同样的,我们还是需要遍历完所有节点。但是递归的好处是每次返回的都是“backward",通过这个特点,我们使用一个counter变量,在递归返回的时候,记录返回经过的节点(Java不如C#,没有ref参数,所以只能用一个数组记录这个counter变量以达到引用的效果)。这样当counter到打n的时候,我们知道,哦,好啦这个当前节点就是我们要删除的节点咯。所以,instead of直接返回head节点,我们返回删除节点的next,这样,在递归调用再次返回的时候,pre的next就指向了删除节点的next咯。
好吧,承认实际上这也是遍历了两次链表。。。:<
解法三: 为了减少遍历,我们还可以用两个指针slow和fast,fast先走n步。then,slow和fast共同进步直到fast走到尾巴。Code在这里。
LeetCode 笔记系列四 Remove Nth Node From End of List的更多相关文章
- LeetCode解题报告—— 4Sum & Remove Nth Node From End of List & Generate Parentheses
1. 4Sum Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + ...
- leetcode第19题--Remove Nth Node From End of List
Problem: Given a linked list, remove the nth node from the end of list and return its head. For exam ...
- LeetCode之“链表”:Remove Nth Node From End of List
题目链接 题目要求: Given a linked list, remove the nth node from the end of list and return its head. For ex ...
- LeetCode题解:(19) Remove Nth Node From End of List
题目说明 Given a linked list, remove the nth node from the end of list and return its head. For example, ...
- LeetCode(19) Remove Nth Node From End of List
题目 Given a linked list, remove the nth node from the end of list and return its head. For example, G ...
- 【leetcode❤python】 19. Remove Nth Node From End of List
#-*- coding: UTF-8 -*-#双指针思想,两个指针相隔n-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针的后继就是要删除的节点# Definition for sin ...
- leetcode个人题解——#19 Remove Nth Node From End of List
思路:设置两个指针,其中第二个指针比第一个延迟n个元素,这样,当第二个指针遍历到指针尾部时,对第一个指针进行删除操作. 当然,这题要注意一些边界值,比如输入[1,2] n=2时如果按照思路走会指向未分 ...
- LeetCode: Remove Nth Node From End of List 解题报告
Remove Nth Node From End of List Total Accepted: 46720 Total Submissions: 168596My Submissions Quest ...
- 《LeetBook》leetcode题解(19):Remove Nth Node From End of List[E]——双指针解决链表倒数问题
我现在在做一个叫<leetbook>的开源书项目,把解题思路都同步更新到github上了,需要的同学可以去看看 这个是书的地址: https://hk029.gitbooks.io/lee ...
随机推荐
- Python 爬虫实例(4)—— 爬取网易新闻
自己闲来无聊,就爬取了网易信息,重点是分析网页,使用抓包工具详细的分析网页的每个链接,数据存储在sqllite中,这里只是简单的解析了新闻页面的文字信息,并未对图片信息进行解析 仅供参考,不足之处请指 ...
- Linux iptables常用命令
iptables 是 Linux 中重要的访问控制手段,是俗称的 Linux 防火墙系统的重要组成部分.这里记录了iptables 防火墙规则的一些常用的操作指令. 下面的操作以 CentOS 为基础 ...
- atitit.研发管理--标准化流程总结---java开发环境与项目部署环境的搭建工具包总结
atitit.研发管理--标准化流程总结---java开发环境与项目部署环境的搭建工具包总结 1. ide系列(只开发环境需要,但部署环境也做好放上,很有用) 1 2. web服务器+sdk+网站程序 ...
- python 获取当前时间的用法
1.先导入库:import datetime 2.获取当前日期和时间:now_time = datetime.datetime.now() 3.格式化成我们想要的日期:strftime() 比如:“2 ...
- LINK : fatal error LNK1104
今天本来想试试opencv的,于是就在自己的机子上部署一下试试,结果一直遇到这个错误:LINK : fatal error LNK1104 环境:win7 64位 vs2012 opencv 2.4. ...
- nyoj16矩形嵌套(第一道dp关于dag的题目)
http://acm.nyist.net/JudgeOnline/problem.php?pid=16 题意:有n个矩形,每个矩形可以用a,b来描述,表示长和宽.矩形X(a,b)可以嵌套在矩形Y(c, ...
- windows下wim配置成IDE
1.配置文件_wimrc set fileencodings=utf-,ucs-bom,cp936,big5 set fileencoding=utf- source $VIMRUNTIME/vimr ...
- matlab_legend_使用
matlab legend 使用 用Matlab画图时,有时候需要对各种图标进行标注,例如,用“+”代表A的运动情况,“*”代表B的 运动情况.legend函数的基本用法是LEGEND(string1 ...
- ip: either "dev" is duplicate, or "type" is garbage
Driver installation Nothing has to be done for the APF51Dev, the APF28Dev and the APF6Dev. For the A ...
- sqlite笔记(akaedu)
1.创建sql表create table student(id integer primary key, name text, score integer): 2.插入一条记录insert into ...