83. Remove Duplicates from Sorted List
題目網址:https://leetcode.cn/problems/remove-duplicates-from-sorted-list/
題意:給一 sorted linked list, 刪除 linked list 所有重複的元素, 讓每種元素恰好出現一次。
Solution:
想法:比較當前 node 和 下一個 node 的 val, 若相同則刪除下一個, 直到下一個的值不同, cur 才前進
class Solution {public: ListNode* deleteDuplicates(ListNode* head) { ListNode *curr = head; while (curr && curr->next) { if (curr->val == curr->next->val) { curr->next = curr->next->next; ...
203. Remove Linked List Elements
題目網址:https://leetcode.cn/problems/remove-linked-list-elements
題意:給一整數 val, 刪除 linked list 中所有 node.val == val 的 node。
Solution:
想法:用 dummy 來指向 head, pre 則記住當前 node 的前一個 node初始化 pre 為 dummy(head 的前一個 node)
class Solution {public: ListNode* removeElements(ListNode* head, int val) { // dummy 指向 link-list 之 head const ListNode *dummy = new ListNode(0, head); ListNode *curr = head, *prev = dummy; while (curr) { if (curr->val == val) ...
190. Reverse Bits
題目網址:https://leetcode.cn/problems/reverse-bits/
題意:給一無號整數 n, 請將其二進制進行反轉。
Solution:
想法:每次先把 res 的最右 bit 設為 0(左移一位, 最右 bit 補 0), 然後取得 n 的最右 bit(對 n 的最右 bit 取 OR), 做完後將 n 右移一位(捨棄最右 bit)
class Solution {public: uint32_t reverseBits(uint32_t n) { uint32_t res = 0; for (int i = 0; i < 32; ++i) { res <<= 1; // 最右 bit 設 0 res |= (n & 1); // 得到 n 的最右 bit n >>= 1; // 捨棄最右 bit } return res; }& ...
206. Reverse Linked List
題目網址:https://leetcode.cn/problems/reverse-linked-list/
題意:反轉 linked-list。
Solution:
想法:必須要有 prev, nxt 來記住前一個 node 和 下一個 node
class Solution {public: ListNode* reverseList(ListNode* head) { ListNode *prev = nullptr, *nxt = nullptr; while (head) { nxt = head->next; head->next = prev; prev = head; head = nxt; } return prev; }};
time:$O(n)$ ➔ 遍歷整個 linked list
space:$O(1)$ ➔ 只需要常數空 ...
136. Single Number
題目網址:https://leetcode.cn/problems/single-number/
題意:給一非空的 array nums, 當中只有一個數 n1 只出現一次, 找出 n1。
Solution:
想法:利用 XOR 的特性, a ^ a = 0 且 0 ^ b = b, 還有交換性e.g. b ^ a ^ b = a ^ (b ^ b) = a ^ 0 = a
class Solution {public: int singleNumber(vector<int>& nums) { int res = 0; for (const auto& num : nums) { res ^= num; } return res; }};
time:$O(n)$ ➔ 遍歷 nums
space:$O(1)$ ➔ 只需要常數空間