算法刷题记录 Day4
Date: 2024.02.24
补之前漏的一天。
leetcode 24. 两两交换链表中的结点. 时间On,空间O1;
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == nullptr || head->next == nullptr)
return head;
ListNode* dummy_head = new ListNode(0, head->next);
while(1){
//1.当前结点的->next->next为空 或 指向->next->next结点,并在结束后break;
if(head->next->next == nullptr || head->next->next->next == nullptr){
ListNode* tmp = head->next;
head->next = head->next->next;
tmp->next = head;
break;
}
//2.当前结点的->next->next->next不为空,则当前节点指向该结点
else{
ListNode* tmp = head->next->next;
head->next->next = head;
head->next = tmp->next;
head = tmp;
}
}
return dummy_head->next;
}
};
leetcode 19. 删除链表的倒数第N个结点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy_head = new ListNode(0, head);
ListNode* fast = dummy_head;
ListNode* slow = dummy_head;
// fast先走n步
for(int i=0; i<n; i++){
fast = fast->next;
}
// slow和fast一起走k-n步,k为结点数(不包括dummy node.)
while(fast->next){
fast = fast->next;
slow = slow->next;
}
// 此时,slow的下个结点为需要删除的结点。
ListNode* tmp = slow->next;
slow->next = tmp->next;
delete tmp;
return dummy_head->next;
}
};
leetcode 面试题02.07. 链表相交 时间On, 空间O1
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
//1. 统计两链表长度
int lens_A = 0;
int lens_B = 0;
ListNode* tmpA = headA;
ListNode* tmpB = headB;
while(tmpA){
tmpA = tmpA->next;
lens_A++;
}
while(tmpB){
tmpB = tmpB->next;
lens_B++;
}
//2. 提前移动较长的链表至剩余长度相同
tmpA = headA;
tmpB = headB;
if(lens_A >= lens_B){
for(int i=0; i<(lens_A-lens_B); i++){
tmpA = tmpA->next;
}
}
else{
for(int i=0; i<(lens_B-lens_A); i++){
tmpB = tmpB->next;
}
}
//3. 逐个比较直至为空或相等
while(tmpA != tmpB && tmpA){
tmpA = tmpA->next;
tmpB = tmpB->next;
}
if(tmpA == nullptr){
return nullptr;
}
else{
return tmpA;
}
}
};
leetcode 142. 环形链表ii.
// 快慢指针,时间On, 空间O1
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* dummy_head = new ListNode(0);
dummy_head->next = head;
ListNode* slow = dummy_head;
ListNode* fast = dummy_head;
while(1){
if(fast == nullptr || fast->next == nullptr)
return nullptr;
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
break;
}
while(dummy_head != slow){
dummy_head = dummy_head->next;
slow = slow->next;
}
return slow;
}
};
//哈希集合, 时间On, 空间On
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode*> mp;
while(head){
mp.insert(head);
head = head->next;
if(head != nullptr && mp.count(head)){
return head;
}
}
return nullptr;
}
};