236. 二叉树的最近公共祖先
- 236. 二叉树的最近公共祖先\
- 思路:递归,如注释
- 时间和空间:O(n)
class Solution {
public:TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {if(root == nullptr || root == q || root == p) return root;TreeNode* left = lowestCommonAncestor(root->left, p, q);TreeNode* right = lowestCommonAncestor(root->right, p, q);if(!left && !right) return nullptr;if(left && !right) return left;if(!left && right) return right;return root;}
};
234. 回文链表
- 234. 回文链表
- 思路1:如注释
- 时间和空间:O(n)
class Solution {
public:bool isPalindrome(ListNode* head) {vector<int>v;while(head){v.push_back(head->val);head = head->next;}int size = v.size();for(int i = 0; i < size / 2; i++){if(v[i] != v[size - 1 - i]){return false;}}return true;}
};
- 思路2:快慢指针找到链表中点,后一段链表翻转,然后比较两个链表是否相同
- 时间:O(n),空间:O(1)
class Solution {
public:ListNode* findMiddle(ListNode* head){ListNode* fast = head, *slow = head;while(fast->next && fast->next->next){fast = fast->next->next;slow = slow->next;}return slow;}ListNode* reverseList(ListNode* head){ListNode* pre = nullptr, *cur = head, *next = nullptr;while(cur){next = cur->next;cur->next = pre;pre = cur;cur = next;}return pre;}bool isPalindrome(ListNode* head) {if(head == nullptr) return true;ListNode* middle = findMiddle(head);ListNode* right = reverseList(middle->next);ListNode* p = head, *q = right;while(p && q){if(p->val != q->val){return false;}p = p->next;q = q->next;}return true;}
};
141. 环形链表
- 141. 环形链表
- 思路:如注释
- 时间:O(n);空间:O(1)
class Solution {
public:bool hasCycle(ListNode *head) {if(head == nullptr || head->next == nullptr) return false;ListNode* p = head, *q = head;while(q && q->next){p = p->next;q = q->next->next;if(q == p){return true;}}return false;}
};