// 本题只需要注意的是维护两个指针分别指向当前节点后后一个节点,每次移动位置向后移动,最后处理原本的头节点指向null classSolution { public: ListNode *reverseList(ListNode *head){ if (!head) returnnullptr; auto a = head, b = head->next; while (b) { auto c = b->next; b->next = a; a = b; b = c; } head->next = nullptr; return a; } };
voidinsert(string word){ int k = 0, n = word.size(), j; for (int i = 0; i < n; i++) { j = word[i] - 'a'; if (!s[k][j]) s[k][j] = ++idx; k = s[k][j]; } ++cnt[k]; }
boolsearch(string word){ int k = 0, n = word.size(), j; for (int i = 0; i < n; i++) { j = word[i] - 'a'; if (!s[k][j]) returnfalse; else k = s[k][j]; } return cnt[k]; }
boolstartsWith(string prefix){ int k = 0, n = prefix.size(), j; for (int i = 0; i < n; i++) { j = prefix[i] - 'a'; if (!s[k][j]) returnfalse; else k = s[k][j]; } returntrue; } };
classSolution { public: intquick_select(vector<int> &nums, int l, int r, int k){ if (l == r) return nums[l]; int mid = nums[(l + r) >> 1]; int i = l - 1, j = r + 1; while (i < j) { while (nums[++i] > mid); while (nums[--j] < mid); if (i < j) swap(nums[i], nums[j]); } if (k <= j) returnquick_select(nums, l, j, k); elsereturnquick_select(nums, j + 1, r, k); }
intfindKthLargest(vector<int> &nums, int k){ returnquick_select(nums, 0, nums.size() - 1, k - 1); } };
intdfs(TreeNode *root, TreeNode *p, TreeNode *q){ if (!root) return0; int state = dfs(root->left, p, q); if (root == p) state |= 1; if (root == q) state |= 2; state |= dfs(root->right, p, q); if (state == 3 && !res) return res = root; return state; } };
classSolution { public: inthIndex(vector<int> &citations){ int len = citations.size(), res = 0; sort(citations.begin(), citations.end()); for (int i = 0; i < citations.size(); ++i) if (len - i <= citations[i]) { res = len - i; break; } return res; } };