当前位置:网站首页>Leetcode skimming: the penultimate node in the linked list
Leetcode skimming: the penultimate node in the linked list
2022-07-22 06:24:00 【Scattered prosperity for a lifetime, and colored glass for a li】
1. The... In the linked list k Nodes
Enter a linked list , Output the last number in the list k Nodes . In order to conform to the habits of most people , From 1 Start counting , That is, the tail node of the list is the last 1 Nodes .
for example , A list has 6 Nodes , Start from the beginning , Their values, in turn, are 1、2、3、4、5、6. The last of the list 3 Each node has a value of 4 The node of .
Be careful : This question once appeared in meituan's written test algorithm question .
Example :
1. Hash table implementation
Here we can use hash table to solve this problem :
First traverse the list , Store the nodes in the linked list in the hash table in the form of key value pairs , The key of the hash table is the location of the node ( from 1 Start ), The value is the current node , Because of the penultimate k The node is exactly the positive number n-k+1 individual (n Is the length of the linked list ), So the index in the hash table is n-k Of value, Take it out of the hash table and return it .
The specific code is as follows :
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
Map<Integer,ListNode> hash=new HashMap<>();
ListNode p=head;
int num=1;
while(p!=null){
hash.put(num,p);
p=p.next;
num++;
}
p=hash.get(num-k);
return p;
}
}
2. Time complexity analysis
Because time is a traversal of the linked list , So the time complexity is O ( n ) O(n) O(n), Here, a hash table is used to store the corresponding linked list location and linked list node , So the complexity of space is O ( n ) O(n) O(n), The specific code is in LeetCode The implementation of is as follows :
3. In order to find
According to the previous analysis , Last but not least k The first element node is the positive number n-k+1 Nodes , So the key to the problem is to find out the total number of linked list nodes first n, Point the pointer to the n-k+1 The problem can be solved by adding a linked list node and returning , The specific code is as follows :
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
int n=0;
ListNode p=null;
// Determine the length of the linked list
for(p=head;p!=null;p=p.next){
n++;
}
p=head;
for(int i=0;i<n-k;i++){
p=p.next;
}
return p;
}
}
Be careful : Find the first n-k+1 When there are linked list nodes , because p Point again to head Head node , For the first element , So just move n-k This can point to the... Of the linked list n-k+1 Nodes .
4. Time complexity analysis
Because the implementation time of this algorithm is still the traversal of the linked list , The first traversal is to determine the length of the linked list , The second iteration is to find the second n-k+1 List nodes . So the time complexity is still O ( n ) O(n) O(n), The hash table storage node is not used in this algorithm implementation , So the space complexity is zero O ( 1 ) O(1) O(1), The specific algorithm is LeetCode The implementation of is as follows :
5. Fast and slow pointer to achieve
The idea of fast and slow pointer . We will the first pointer \textit{fast}fast The list points to k + 1 Nodes , The second pointer slow \textit{slow} slow Point to the first node of the list , Now the pointer fast \textit{fast} fast And slow \textit{slow} slow There is just a gap between the two k k k Nodes . At this time, the two pointers move backward synchronously , When the first pointer fast \textit{fast} fast When you reach the empty node at the end of the linked list , Now slow \textit{slow} slow The pointer just points to the penultimate... Of the linked list k k k Nodes .
Let's start with fast \textit{fast} fast Point to the head node of the list , Then walk back k k k Step , Now fast \textit{fast} fast The pointer just points to the... Of the linked list k + 1 k + 1 k+1 Nodes .
Let's start with slow \textit{slow} slow Point to the head node of the list , meanwhile slow \textit{slow} slow And fast \textit{fast} fast Step backward synchronously , When fast \textit{fast} fast When the pointer points to the empty node at the end of the linked list , Then return to slow \textit{slow} slow Point to the node .
The specific code is as follows :
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode fast=head;
ListNode slow=head;
// take fast The pointer moves forward k position
while(fast!=null && k>0){
fast=fast.next;
k--;
}
// Move the speed pointer backward at the same time
while(fast!=null){
fast=fast.next;
slow=slow.next;
}
return slow;
}
}
6.GIF Moving pictures show
Here's a list {1,2,3,4,5} For example , Look for the last 2 An element of GIF The dynamic diagram is as follows :
7. Time complexity analysis
The implementation of this algorithm , Here is still only the traversal of the linked list , So the time complexity is zero O ( n ) O(n) O(n), The space complexity is O ( 1 ) O(1) O(1). The specific code is in LeetCode The implementation of is as follows :
边栏推荐
- NETCORE - Middleware (1)
- Leetode 416. Divide equal sum subsets
- Floating profile and floating features
- Question 2 about interview
- Outdoor resource optical fiber management
- Haproxy2.6 load installation configuration
- 数据中心线缆管理
- Episode 1 best B tutorial of VMware virtual machine installation (12 days)
- 3D转换之三维坐标系,透视旋转等基础知识
- How to realize visualization of basic equipment efficiently
猜你喜欢
leetcode 938. The range and of binary search tree
β-环糊精衍生物接枝羟丙基壳聚糖水凝胶/羧基改性壳聚糖固载环糊精水凝胶微球的制备
Typora beta expired solution
聚醚/聚丙烯酰胺-竣甲基/聚丙烯酰胺/粒状聚N-异丙基丙烯酰胺壳聚糖水凝胶的制备方法
动画,及动画的基本使用
Discussion on passing D shield JSP webshell+ ice scorpion avoiding killing horses
这次和GrowingIO工程师一起搞事情 | StartDT Hackathon
Automatic generation of computer room visual management labels
Compound modified chitosan hydrogel: preparation of acrylic acid grafting / polyvinyl alcohol / temperature sensitive icariin / aldehyde imine chitosan hydrogel
leetcode 310. Minimum height tree
随机推荐
开户做期货那家公司手续费低 安全
Preparation method of polyether / polyacrylamide monomethyl / Polyacrylamide / granular poly (N-isopropylacrylamide) chitosan hydrogel
同城订单同城送,爆单依旧得心应手!
leetcode 376.摆动序列
剑指 Offer II 099. 最小路径之和
Feynman learning method
Haproxy2.6 load installation configuration
Western Agricultural University C plus
Set the background color, background range, Sprite chart, gradient, radial gradient, etc
DOM之事件代理(二)
C multithreading and asynchronism (II) -- detailed explanation of task and async/await
Importance of data center operation and maintenance management skills
Episode 1 VMware Virtual Machine installation Best B tutoriel (12 jours)
What is the culprit of the failure of digital transformation?
DOM event proxy (2)
leetcode 1413.逐步求和得到正数的最小值
Bypass some dog SQL and XSS
第2集 vmware虚拟机安装最牛B教程(13天)
The mobile R & D platform EMAS 3.0 is newly upgraded. Welcome to Alibaba cloud's official website to search EMAS for experience
leetcode 1380. 矩阵中的幸运数