Add python, java, and cpp code for sleected_coding_interview.

This commit is contained in:
krahets
2025-12-30 08:18:26 +08:00
parent c27d12f2d2
commit c9e6a10f0d
371 changed files with 14260 additions and 0 deletions

View File

@@ -0,0 +1,69 @@
/*
* File: ListNode.hpp
* Created Time: 2025-12-30
* Author: krahets
*/
#pragma once
#include <iostream>
#include <vector>
using namespace std;
/**
* @brief Definition for a singly-linked list node
*
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {
}
};
/**
* @brief Generate a linked list with a vector
*
* @param list
* @return ListNode*
*/
ListNode *vectorToLinkedList(vector<int> list) {
ListNode *dum = new ListNode(0);
ListNode *head = dum;
for (int val : list) {
head->next = new ListNode(val);
head = head->next;
}
return dum->next;
}
/**
* @brief Get a list node with specific value from a linked list
*
* @param head
* @param val
* @return ListNode*
*/
ListNode *getListNode(ListNode *head, int val) {
while (head != nullptr && head->val != val) {
head = head->next;
}
return head;
}
/**
* @brief Definition for a list node with random pointer
*
*/
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = nullptr;
random = nullptr;
}
};

View File

@@ -0,0 +1,191 @@
/*
* File: PrintUtil.hpp
* Created Time: 2025-12-30
* Author: krahets
*/
#pragma once
#include "ListNode.hpp"
#include "TreeNode.hpp"
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
class PrintUtil {
public:
/**
* @brief Find an element in a vector
*
* @tparam T
* @param vec
* @param ele
* @return int
*/
template <typename T> static int vecFind(const vector<T> &vec, T ele) {
int j = INT_MAX;
for (int i = 0; i < vec.size(); i++) {
if (vec[i] == ele) {
j = i;
}
}
return j;
}
/**
* @brief Concatenate a vector with a delim
*
* @tparam T
* @param delim
* @param vec
* @return string
*/
template <typename T> static string strJoin(const string &delim, const T &vec) {
ostringstream s;
for (const auto &i : vec) {
if (&i != &vec[0]) {
s << delim;
}
s << i;
}
return s.str();
}
/**
* @brief Repeat a string for n times
*
* @param str
* @param n
* @return string
*/
static string strRepeat(string str, int n) {
ostringstream os;
for (int i = 0; i < n; i++)
os << str;
return os.str();
}
/**
* @brief Get the Vector String object
*
* @tparam T
* @param list
* @return string
*/
template <typename T> static string getVectorString(vector<T> &list) {
return "[" + strJoin(", ", list) + "]";
}
/**
* @brief Print a vector
*
* @tparam T
* @param list
*/
template <typename T> static void printVector(vector<T> &list) {
cout << getVectorString(list) << '\n';
}
/**
* @brief Print a vector matrix
*
* @tparam T
* @param matrix
*/
template <typename T> static void printVectorMatrix(vector<vector<T>> &matrix) {
cout << "[" << '\n';
for (vector<T> &list : matrix)
cout << " " + getVectorString(list) + "," << '\n';
cout << "]" << '\n';
}
/**
* @brief Print a linked list
*
* @param head
*/
static void printLinkedList(ListNode *head) {
vector<int> list;
while (head != nullptr) {
list.push_back(head->val);
head = head->next;
}
cout << strJoin(" -> ", list) << '\n';
}
/**
* @brief This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
struct Trunk {
Trunk *prev;
string str;
Trunk(Trunk *prev, string str) {
this->prev = prev;
this->str = str;
}
};
/**
* @brief Helper function to print branches of the binary tree
*
* @param p
*/
static void showTrunks(Trunk *p) {
if (p == nullptr) {
return;
}
showTrunks(p->prev);
cout << p->str;
}
/**
* @brief The interface of the tree printer
*
* @param root
*/
static void printTree(TreeNode *root) {
printTree(root, nullptr, false);
}
/**
* @brief Print a binary tree
*
* @param root
* @param prev
* @param isLeft
*/
static void printTree(TreeNode *root, Trunk *prev, bool isLeft) {
if (root == nullptr) {
return;
}
string prev_str = " ";
Trunk *trunk = new Trunk(prev, prev_str);
printTree(root->right, trunk, true);
if (!prev) {
trunk->str = "———";
} else if (isLeft) {
trunk->str = "/———";
prev_str = " |";
} else {
trunk->str = "\\———";
prev->str = prev_str;
}
showTrunks(trunk);
cout << " " << root->val << endl;
if (prev) {
prev->str = prev_str;
}
trunk->str = " |";
printTree(root->left, trunk, false);
}
};

View File

@@ -0,0 +1,70 @@
/*
* File: TreeNode.hpp
* Created Time: 2025-12-30
* Author: krahets
*/
#pragma once
#include <climits>
#include <queue>
#include <vector>
using namespace std;
/**
* @brief Definition for a binary tree node
*
*/
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {
}
};
/**
* @brief Generate a binary tree with a vector
*
* @param list
* @return TreeNode*
*/
TreeNode *vectorToTree(vector<int> list) {
if (list.empty() || list[0] == INT_MAX) return nullptr;
TreeNode *root = new TreeNode(list[0]);
queue<TreeNode *> que;
que.emplace(root);
int i = 1;
while (!que.empty() && i < list.size()) {
TreeNode *node = que.front();
que.pop();
if (i < list.size() && list[i] != INT_MAX) {
node->left = new TreeNode(list[i]);
que.emplace(node->left);
}
i++;
if (i < list.size() && list[i] != INT_MAX) {
node->right = new TreeNode(list[i]);
que.emplace(node->right);
}
i++;
}
return root;
}
/**
* @brief Get a tree node with specific value in a binary tree
*
* @param root
* @param val
* @return TreeNode*
*/
TreeNode *getTreeNode(TreeNode *root, int val) {
if (root == nullptr)
return nullptr;
if (root->val == val)
return root;
TreeNode *left = getTreeNode(root->left, val);
TreeNode *right = getTreeNode(root->right, val);
return left != nullptr ? left : right;
}

View File

@@ -0,0 +1,27 @@
/*
* File: include.hpp
* Created Time: 2025-12-30
* Author: krahets
*/
#pragma once
#include <algorithm>
#include <climits>
#include <deque>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "ListNode.hpp"
#include "PrintUtil.hpp"
#include "TreeNode.hpp"
using namespace std;

View File

@@ -0,0 +1,33 @@
/*
* File: lc_101_symmetric_tree_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool isSymmetric(TreeNode* root) {
return root == nullptr || recur(root->left, root->right);
}
private:
bool recur(TreeNode* L, TreeNode* R) {
if (L == nullptr && R == nullptr) return true;
if (L == nullptr || R == nullptr || L->val != R->val) return false;
return recur(L->left, R->right) && recur(L->right, R->left);
}
};
int main() {
// ======= Test Case =======
TreeNode* root = vectorToTree({1, 2, 2, 3, 4, 4, 3});
// ====== Driver Code ======
Solution* slt = new Solution();
bool res = slt->isSymmetric(root);
cout << (res ? "true" : "false") << endl;
return 0;
}

View File

@@ -0,0 +1,41 @@
/*
* File: lc_102_binary_tree_level_order_traversal_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
queue<TreeNode*> que;
vector<vector<int>> res;
if (root != nullptr) que.push(root);
while (!que.empty()) {
vector<int> tmp;
for(int i = que.size(); i > 0; --i) {
root = que.front();
que.pop();
tmp.push_back(root->val);
if (root->left != nullptr) que.push(root->left);
if (root->right != nullptr) que.push(root->right);
}
res.push_back(tmp);
}
return res;
}
};
int main() {
// ======= Test Case =======
TreeNode* root = vectorToTree({3, 9, 20, INT_MAX, INT_MAX, 15, 7});
// ====== Driver Code ======
Solution* slt = new Solution();
vector<vector<int>> res = slt->levelOrder(root);
PrintUtil::printVectorMatrix(res);
return 0;
}

View File

@@ -0,0 +1,56 @@
/*
* File: lc_103_binary_tree_zigzag_level_order_traversal_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
deque<TreeNode*> deque;
vector<vector<int>> res;
if (root != NULL) deque.push_back(root);
while (!deque.empty()) {
// 打印奇数层
vector<int> tmp;
for(int i = deque.size(); i > 0; i--) {
// 从左向右打印
TreeNode* node = deque.front();
deque.pop_front();
tmp.push_back(node->val);
// 先左后右加入下层节点
if (node->left != NULL) deque.push_back(node->left);
if (node->right != NULL) deque.push_back(node->right);
}
res.push_back(tmp);
if (deque.empty()) break; // 若为空则提前跳出
// 打印偶数层
tmp.clear();
for(int i = deque.size(); i > 0; i--) {
// 从右向左打印
TreeNode* node = deque.back();
deque.pop_back();
tmp.push_back(node->val);
// 先右后左加入下层节点
if (node->right != NULL) deque.push_front(node->right);
if (node->left != NULL) deque.push_front(node->left);
}
res.push_back(tmp);
}
return res;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,41 @@
/*
* File: lc_103_binary_tree_zigzag_level_order_traversal_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
queue<TreeNode*> que;
vector<vector<int>> res;
if (root != NULL) que.push(root);
while (!que.empty()) {
vector<int> tmp;
for(int i = que.size(); i > 0; i--) {
TreeNode* node = que.front();
que.pop();
tmp.push_back(node->val);
if (node->left != NULL) que.push(node->left);
if (node->right != NULL) que.push(node->right);
}
if (res.size() % 2 == 1) reverse(tmp.begin(),tmp.end());
res.push_back(tmp);
}
return res;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,28 @@
/*
* File: lc_104_maximum_depth_of_binary_tree_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
int main() {
// ======= Test Case =======
TreeNode* root = vectorToTree({3, 9, 20, INT_MAX, INT_MAX, 15, 7});
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->maxDepth(root);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,40 @@
/*
* File: lc_104_maximum_depth_of_binary_tree_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
vector<TreeNode*> que;
que.push_back(root);
int res = 0;
while (!que.empty()) {
vector<TreeNode*> tmp;
for(TreeNode* node : que) {
if (node->left != nullptr) tmp.push_back(node->left);
if (node->right != nullptr) tmp.push_back(node->right);
}
que = tmp;
res++;
}
return res;
}
};
int main() {
// ======= Test Case =======
TreeNode* root = vectorToTree({3, 9, 20, INT_MAX, INT_MAX, 15, 7});
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->maxDepth(root);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,40 @@
/*
* File: lc_105_construct_binary_tree_from_preorder_and_inorder_traversal_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
this->preorder = preorder;
for(int i = 0; i < inorder.size(); i++)
dic[inorder[i]] = i;
return recur(0, 0, inorder.size() - 1);
}
private:
vector<int> preorder;
unordered_map<int, int> dic;
TreeNode* recur(int root, int left, int right) {
if (left > right) return nullptr; // 递归终止
TreeNode* node = new TreeNode(preorder[root]); // 建立根节点
int i = dic[preorder[root]]; // 划分根节点、左子树、右子树
node->left = recur(root + 1, left, i - 1); // 开启左子树递归
node->right = recur(root + i - left + 1, i + 1, right); // 开启右子树递归
return node; // 回溯返回根节点
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,38 @@
/*
* File: lc_10_regular_expression_matching_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.size() + 1, n = p.size() + 1;
vector<vector<bool>> dp(m, vector<bool>(n, false));
dp[0][0] = true;
for(int j = 2; j < n; j += 2)
dp[0][j] = dp[0][j - 2] && p[j - 1] == '*';
for(int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) {
dp[i][j] = p[j - 1] == '*' ?
dp[i][j - 2] || dp[i - 1][j] && (s[i - 1] == p[j - 2] || p[j - 2] == '.'):
dp[i - 1][j - 1] && (p[j - 1] == '.' || s[i - 1] == p[j - 1]);
}
}
return dp[m - 1][n - 1];
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,45 @@
/*
* File: lc_10_regular_expression_matching_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.size() + 1, n = p.size() + 1;
vector<vector<bool>> dp(m, vector<bool>(n, false));
dp[0][0] = true;
// 初始化首行
for(int j = 2; j < n; j += 2)
dp[0][j] = dp[0][j - 2] && p[j - 1] == '*';
// 状态转移
for(int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) {
if (p[j - 1] == '*') {
if (dp[i][j - 2]) dp[i][j] = true; // 1.
else if (dp[i - 1][j] && s[i - 1] == p[j - 2]) dp[i][j] = true; // 2.
else if (dp[i - 1][j] && p[j - 2] == '.') dp[i][j] = true; // 3.
} else {
if (dp[i - 1][j - 1] && s[i - 1] == p[j - 1]) dp[i][j] = true; // 1.
else if (dp[i - 1][j - 1] && p[j - 1] == '.') dp[i][j] = true; // 2.
}
}
}
return dp[m - 1][n - 1];
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,36 @@
/*
* File: lc_110_balanced_binary_tree_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool isBalanced(TreeNode* root) {
return recur(root) != -1;
}
private:
int recur(TreeNode* root) {
if (root == nullptr) return 0;
int left = recur(root->left);
if (left == -1) return -1;
int right = recur(root->right);
if (right == -1) return -1;
return abs(left - right) < 2 ? max(left, right) + 1 : -1;
}
};
int main() {
// ======= Test Case =======
TreeNode* root = vectorToTree({3, 9, 20, INT_MAX, INT_MAX, 15, 7});
// ====== Driver Code ======
Solution* slt = new Solution();
bool res = slt->isBalanced(root);
cout << (res ? "true" : "false") << endl;
return 0;
}

View File

@@ -0,0 +1,33 @@
/*
* File: lc_110_balanced_binary_tree_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool isBalanced(TreeNode* root) {
if (root == nullptr) return true;
return abs(depth(root->left) - depth(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
private:
int depth(TreeNode* root) {
if (root == nullptr) return 0;
return max(depth(root->left), depth(root->right)) + 1;
}
};
int main() {
// ======= Test Case =======
TreeNode* root = vectorToTree({3, 9, 20, INT_MAX, INT_MAX, 15, 7});
// ====== Driver Code ======
Solution* slt = new Solution();
bool res = slt->isBalanced(root);
cout << (res ? "true" : "false") << endl;
return 0;
}

View File

@@ -0,0 +1,40 @@
/*
* File: lc_113_path_sum_ii_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
recur(root, targetSum);
return res;
}
private:
vector<vector<int>> res;
vector<int> path;
void recur(TreeNode* root, int tar) {
if (root == nullptr) return;
path.push_back(root->val);
tar -= root->val;
if (tar == 0 && root->left == nullptr && root->right == nullptr)
res.push_back(path);
recur(root->left, tar);
recur(root->right, tar);
path.pop_back();
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,32 @@
/*
* File: lc_11_container_with_most_water_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int maxArea(vector<int>& height) {
int i = 0, j = height.size() - 1, res = 0;
while(i < j) {
res = height[i] < height[j] ?
max(res, (j - i) * height[i++]):
max(res, (j - i) * height[j--]);
}
return res;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,32 @@
/*
* File: lc_121_best_time_to_buy_and_sell_stock_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int maxProfit(vector<int>& prices) {
int cost = INT_MAX, profit = 0;
for (int price : prices) {
cost = min(cost, price);
profit = max(profit, price - cost);
}
return profit;
}
};
int main() {
// ======= Test Case =======
vector<int> prices = {7, 1, 5, 3, 6, 4};
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->maxProfit(prices);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,30 @@
/*
* File: lc_136_single_number_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int singleNumber(vector<int>& nums) {
int x = 0;
for (int num : nums) // 1. 遍历 nums 执行异或运算
x ^= num;
return x; // 2. 返回出现一次的数字 x
}
};
int main() {
// ======= Test Case =======
vector<int> nums = {2, 2, 1};
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->singleNumber(nums);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,30 @@
/*
* File: lc_138_copy_list_with_random_pointer_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node(int _val) {
val = _val;
next = NULL;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,32 @@
/*
* File: lc_138_copy_list_with_random_pointer_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
// Definition for a Node.
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,35 @@
/*
* File: lc_138_copy_list_with_random_pointer_s3.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
Node* copyRandomList(Node* head) {
Node* cur = head;
Node* dum = new Node(0), *pre = dum;
while(cur != nullptr) {
Node* node = new Node(cur->val); // 复制节点 cur
pre->next = node; // 新链表的 前驱节点 -> 当前节点
// pre->random = "???"; // 新链表的 「 前驱节点 -> 当前节点 」 无法确定
cur = cur->next; // 遍历下一节点
pre = node; // 保存当前新节点
}
return dum->next;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,42 @@
/*
* File: lc_138_copy_list_with_random_pointer_s4.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head == nullptr) return nullptr;
Node* cur = head;
unordered_map<Node*, Node*> map;
// 3. 复制各节点,并建立 “原节点 -> 新节点” 的 Map 映射
while(cur != nullptr) {
map[cur] = new Node(cur->val);
cur = cur->next;
}
cur = head;
// 4. 构建新链表的 next 和 random 指向
while(cur != nullptr) {
map[cur]->next = map[cur->next];
map[cur]->random = map[cur->random];
cur = cur->next;
}
// 5. 返回新链表的头节点
return map[head];
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,52 @@
/*
* File: lc_138_copy_list_with_random_pointer_s5.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head == nullptr) return nullptr;
Node* cur = head;
// 1. 复制各节点,并构建拼接链表
while(cur != nullptr) {
Node* tmp = new Node(cur->val);
tmp->next = cur->next;
cur->next = tmp;
cur = tmp->next;
}
// 2. 构建各新节点的 random 指向
cur = head;
while(cur != nullptr) {
if(cur->random != nullptr)
cur->next->random = cur->random->next;
cur = cur->next->next;
}
// 3. 拆分两链表
cur = head->next;
Node* pre = head, *res = head->next;
while(cur->next != nullptr) {
pre->next = pre->next->next;
cur->next = cur->next->next;
pre = pre->next;
cur = cur->next;
}
pre->next = nullptr; // 单独处理原链表尾节点
return res; // 返回新链表头节点
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,32 @@
/*
* File: lc_1480_running_sum_of_1d_array_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<int> runningSum(vector<int>& nums) {
vector<int> dp(nums.size());
dp[0] = nums[0];
for (int i = 1; i < nums.size(); i++) {
dp[i] = dp[i - 1] + nums[i];
}
return dp;
}
};
int main() {
// ======= Test Case =======
vector<int> nums = {1, 2, 3, 4};
// ====== Driver Code ======
Solution* slt = new Solution();
vector<int> res = slt->runningSum(nums);
PrintUtil::printVector(res);
return 0;
}

View File

@@ -0,0 +1,33 @@
/*
* File: lc_154_find_minimum_in_rotated_sorted_array_ii_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int findMin(vector<int>& nums) {
int i = 0, j = nums.size() - 1;
while (i < j) {
int m = (i + j) / 2;
if (nums[m] > nums[j]) i = m + 1;
else if (nums[m] < nums[j]) j = m;
else j--;
}
return nums[i];
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,39 @@
/*
* File: lc_154_find_minimum_in_rotated_sorted_array_ii_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int findMin(vector<int>& nums) {
int i = 0, j = nums.size() - 1;
while (i < j) {
int m = (i + j) / 2;
if (nums[m] > nums[j]) i = m + 1;
else if (nums[m] < nums[j]) j = m;
else {
int x = i;
for(int k = i + 1; k < j; k++) {
if(nums[k] < nums[x]) x = k;
}
return nums[x];
}
}
return nums[i];
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,31 @@
/*
* File: lc_160_intersection_of_two_linked_lists_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *A = headA, *B = headB;
while (A != B) {
A = A != nullptr ? A->next : headB;
B = B != nullptr ? B->next : headA;
}
return A;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,35 @@
/*
* File: lc_167_two_sum_ii_input_array_is_sorted_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int i = 0, j = numbers.size() - 1;
while (i < j) {
int s = numbers[i] + numbers[j];
if (s < target) i++;
else if (s > target) j--;
else return { i + 1, j + 1 };
}
return {};
}
};
int main() {
// ======= Test Case =======
vector<int> numbers = {2, 7, 11, 15};
int target = 9;
// ====== Driver Code ======
Solution* slt = new Solution();
vector<int> res = slt->twoSum(numbers, target);
PrintUtil::printVector(res);
return 0;
}

View File

@@ -0,0 +1,32 @@
/*
* File: lc_169_majority_element_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int majorityElement(vector<int>& nums) {
int x = 0, votes = 0;
for (int num : nums){
if (votes == 0) x = num;
votes += num == x ? 1 : -1;
}
return x;
}
};
int main() {
// ======= Test Case =======
vector<int> nums = {3, 2, 3};
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->majorityElement(nums);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,35 @@
/*
* File: lc_169_majority_element_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int majorityElement(vector<int>& nums) {
int x = 0, votes = 0, count = 0;
for (int num : nums){
if (votes == 0) x = num;
votes += num == x ? 1 : -1;
}
// 验证 x 是否为众数
for (int num : nums)
if (num == x) count++;
return count > nums.size() / 2 ? x : 0; // 当无众数时返回 0
}
};
int main() {
// ======= Test Case =======
vector<int> nums = {3, 2, 3};
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->majorityElement(nums);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,35 @@
/*
* File: lc_179_largest_number_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> strs;
string res;
for (int i = 0; i < nums.size(); i++)
strs.push_back(to_string(nums[i]));
sort(strs.begin(), strs.end(), [](string& x, string& y){ return y + x < x + y; });
if (strs[0] == "0")
return "0";
for (int i = 0; i < strs.size(); i++)
res.append(strs[i]);
return res;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,48 @@
/*
* File: lc_179_largest_number_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
string largestNumber(vector<int>& nums) {
vector<string> strs;
for (int i = 0; i < nums.size(); i++)
strs.push_back(to_string(nums[i]));
quickSort(strs, 0, strs.size() - 1);
if (strs[strs.size() - 1] == "0")
return "0";
string res;
for (int i = nums.size() - 1; i >=0; i--)
res.append(strs[i]);
return res;
}
private:
void quickSort(vector<string>& strs, int l, int r) {
if (l >= r) return;
int i = l, j = r;
while (i < j) {
while (strs[j] + strs[l] >= strs[l] + strs[j] && i < j) j--;
while (strs[i] + strs[l] <= strs[l] + strs[i] && i < j) i++;
swap(strs[i], strs[j]);
}
swap(strs[i], strs[l]);
quickSort(strs, l, i - 1);
quickSort(strs, i + 1, r);
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,30 @@
/*
* File: lc_1823_find_the_winner_of_the_circular_game_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int findTheWinner(int n, int k) {
int x = 0;
for (int i = 2; i <= n; i++) {
x = (x + k) % i;
}
return x + 1;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,32 @@
/*
* File: lc_191_number_of_1_bits_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int hammingWeight(uint32_t n) {
unsigned int res = 0; // c++ 使用无符号数
while (n != 0) {
res += n & 1;
n >>= 1;
}
return res;
}
};
int main() {
// ======= Test Case =======
uint32_t n = 0b00000000000000000000000000001011;
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->hammingWeight(n);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,32 @@
/*
* File: lc_191_number_of_1_bits_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int hammingWeight(uint32_t n) {
int res = 0;
while (n != 0) {
res++;
n &= n - 1;
}
return res;
}
};
int main() {
// ======= Test Case =======
uint32_t n = 0b00000000000000000000000000001011;
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->hammingWeight(n);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,39 @@
/*
* File: lc_205_isomorphic_strings_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool isIsomorphic(string s, string t) {
unordered_map<char, char> t2s, s2t;
for (int i = 0; i < s.size(); i++) {
char a = s[i], b = t[i];
// 对于已有映射 a -> s2t[a],若和当前字符映射 a -> b 不匹配,
// 说明有一对多的映射关系,则返回 false
// 对于映射 b -> a 也同理
if (s2t.find(a) != s2t.end() && s2t[a] != b ||
t2s.find(b) != t2s.end() && t2s[b] != a)
return false;
s2t[a] = b;
t2s[b] = a;
}
return true;
}
};
int main() {
// ======= Test Case =======
string s = "egg", t = "add";
// ====== Driver Code ======
Solution* slt = new Solution();
bool res = slt->isIsomorphic(s, t);
cout << (res ? "true" : "false") << endl;
return 0;
}

View File

@@ -0,0 +1,34 @@
/*
* File: lc_206_reverse_linked_list_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *cur = head, *pre = nullptr;
while(cur != nullptr) {
ListNode* tmp = cur->next; // 暂存后继节点 cur.next
cur->next = pre; // 修改 next 引用指向
pre = cur; // pre 暂存 cur
cur = tmp; // cur 访问下一节点
}
return pre;
}
};
int main() {
// ======= Test Case =======
ListNode* head = vectorToLinkedList({1, 2, 3, 4, 5});
// ====== Driver Code ======
Solution* slt = new Solution();
ListNode* res = slt->reverseList(head);
PrintUtil::printLinkedList(res);
return 0;
}

View File

@@ -0,0 +1,34 @@
/*
* File: lc_206_reverse_linked_list_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
ListNode* reverseList(ListNode* head) {
return recur(head, nullptr); // 调用递归并返回
}
private:
ListNode* recur(ListNode* cur, ListNode* pre) {
if (cur == nullptr) return pre; // 终止条件
ListNode* res = recur(cur->next, cur); // 递归后继节点
cur->next = pre; // 修改节点引用指向
return res; // 返回反转链表的头节点
}
};
int main() {
// ======= Test Case =======
ListNode* head = vectorToLinkedList({1, 2, 3, 4, 5});
// ====== Driver Code ======
Solution* slt = new Solution();
ListNode* res = slt->reverseList(head);
PrintUtil::printLinkedList(res);
return 0;
}

View File

@@ -0,0 +1,43 @@
/*
* File: lc_215_kth_largest_element_in_an_array_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
quickSort(nums, 0, nums.size() - 1);
return nums[nums.size() - k];
}
private:
void quickSort(vector<int>& nums, int l, int r) {
// 子数组长度为 1 时终止递归
if (l >= r) return;
// 哨兵划分操作(以 nums[l] 作为基准数)
int i = l, j = r;
while (i < j) {
while (i < j && nums[j] >= nums[l]) j--;
while (i < j && nums[i] <= nums[l]) i++;
swap(nums[i], nums[j]);
}
swap(nums[i], nums[l]);
// 递归左(右)子数组执行哨兵划分
quickSort(nums, l, i - 1);
quickSort(nums, i + 1, r);
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,40 @@
/*
* File: lc_215_kth_largest_element_in_an_array_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int findKthLargest(vector<int>& nums, int k) {
return quickSort(nums, k, 0, nums.size() - 1);
}
private:
int quickSort(vector<int>& nums, int k, int l, int r) {
int i = l, j = r;
while (i < j) {
while (i < j && nums[j] >= nums[l]) j--;
while (i < j && nums[i] <= nums[l]) i++;
swap(nums[i], nums[j]);
}
swap(nums[i], nums[l]);
if (i > nums.size() - k) return quickSort(nums, k, l, i - 1);
if (i < nums.size() - k) return quickSort(nums, k, i + 1, r);
// 若基准数索引为 n - k ,则直接返回该元素
return nums[nums.size() - k];
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,42 @@
/*
* File: lc_21_merge_two_sorted_lists_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* dum = new ListNode(0);
ListNode* cur = dum;
while (list1 != nullptr && list2 != nullptr) {
if (list1->val < list2->val) {
cur->next = list1;
list1 = list1->next;
}
else {
cur->next = list2;
list2 = list2->next;
}
cur = cur->next;
}
cur->next = list1 != nullptr ? list1 : list2;
return dum->next;
}
};
int main() {
// ======= Test Case =======
ListNode* list1 = vectorToLinkedList({1, 2, 4});
ListNode* list2 = vectorToLinkedList({1, 3, 4});
// ====== Driver Code ======
Solution* slt = new Solution();
ListNode* res = slt->mergeTwoLists(list1, list2);
PrintUtil::printLinkedList(res);
return 0;
}

View File

@@ -0,0 +1,31 @@
/*
* File: lc_226_invert_binary_tree_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) return nullptr;
TreeNode* tmp = root->left;
root->left = invertTree(root->right);
root->right = invertTree(tmp);
return root;
}
};
int main() {
// ======= Test Case =======
TreeNode* root = vectorToTree({4, 2, 7, 1, 3, 6, 9});
// ====== Driver Code ======
Solution* slt = new Solution();
TreeNode* res = slt->invertTree(root);
PrintUtil::printTree(res);
return 0;
}

View File

@@ -0,0 +1,40 @@
/*
* File: lc_226_invert_binary_tree_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) return nullptr;
stack<TreeNode*> stack;
stack.push(root);
while (!stack.empty())
{
TreeNode* node = stack.top();
stack.pop();
if (node->left != nullptr) stack.push(node->left);
if (node->right != nullptr) stack.push(node->right);
TreeNode* tmp = node->left;
node->left = node->right;
node->right = tmp;
}
return root;
}
};
int main() {
// ======= Test Case =======
TreeNode* root = vectorToTree({4, 2, 7, 1, 3, 6, 9});
// ====== Driver Code ======
Solution* slt = new Solution();
TreeNode* res = slt->invertTree(root);
PrintUtil::printTree(res);
return 0;
}

View File

@@ -0,0 +1,39 @@
/*
* File: lc_230_kth_smallest_element_in_a_bst_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int kthSmallest(TreeNode* root, int k) {
this->k = k;
dfs(root);
return res;
}
private:
int res, k;
void dfs(TreeNode* root) {
if (root == nullptr) return;
dfs(root->left);
if (k == 0) return;
if (--k == 0) res = root->val;
dfs(root->right);
}
};
int main() {
// ======= Test Case =======
TreeNode* root = vectorToTree({3, 1, 4, INT_MAX, 2});
int k = 1;
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->kthSmallest(root, k);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,51 @@
/*
* File: lc_232_implement_queue_using_stacks_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class MyQueue {
private:
std::stack<int> A, B;
public:
MyQueue() {}
void push(int x) {
A.push(x);
}
int pop() {
int peek = this->peek();
B.pop();
return peek;
}
int peek() {
if (!B.empty()) return B.top();
if (A.empty()) return -1;
while (!A.empty()){
B.push(A.top()), A.pop();
}
int res = B.top();
return res;
}
bool empty() {
return A.empty() && B.empty();
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,24 @@
/*
* File: lc_233_number_of_digit_one_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
int high = n / 10;
int cur = n % 10;
int low = 0;
int digit = 1; // 个位
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,26 @@
/*
* File: lc_233_number_of_digit_one_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
while (high != 0 || cur != 0) { // 当 high 和 cur 同时为 0 时,说明已经越过最高位,因此跳出
low += cur * digit; // 将 cur 加入 low ,组成下轮 low
cur = high % 10; // 下轮 cur 是本轮 high 的最低位
high /= 10; // 将本轮 high 最低位删除,得到下轮 high
digit *= 10; // 位因子每轮 × 10
}
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,37 @@
/*
* File: lc_233_number_of_digit_one_s3.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int countDigitOne(int n) {
long digit = 1;
int high = n / 10, cur = n % 10, low = 0, res = 0;
while (high != 0 || cur != 0) {
if (cur == 0) res += high * digit;
else if (cur == 1) res += high * digit + low + 1;
else res += (high + 1) * digit;
low += cur * digit;
cur = high % 10;
high /= 10;
digit *= 10;
}
return res;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,33 @@
/*
* File: lc_235_lowest_common_ancestor_of_a_binary_search_tree_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while (root != nullptr) {
if (root->val < p->val && root->val < q->val) // p,q 都在 root 的右子树中
root = root->right; // 遍历至右子节点
else if (root->val > p->val && root->val > q->val) // p,q 都在 root 的左子树中
root = root->left; // 遍历至左子节点
else break;
}
return root;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,35 @@
/*
* File: lc_235_lowest_common_ancestor_of_a_binary_search_tree_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (p->val > q->val)
swap(p, q);
while (root != nullptr) {
if (root->val < p->val) // p,q 都在 root 的右子树中
root = root->right; // 遍历至右子节点
else if (root->val > q->val) // p,q 都在 root 的左子树中
root = root->left; // 遍历至左子节点
else break;
}
return root;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,30 @@
/*
* File: lc_235_lowest_common_ancestor_of_a_binary_search_tree_s3.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root->val < p->val && root->val < q->val)
return lowestCommonAncestor(root->right, p, q);
if (root->val > p->val && root->val > q->val)
return lowestCommonAncestor(root->left, p, q);
return root;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,31 @@
/*
* File: lc_236_lowest_common_ancestor_of_a_binary_tree_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root == q) return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
if(left == nullptr) return right;
if(right == nullptr) return left;
return root;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,32 @@
/*
* File: lc_236_lowest_common_ancestor_of_a_binary_tree_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == nullptr || root == p || root == q) return root;
TreeNode *left = lowestCommonAncestor(root->left, p, q);
TreeNode *right = lowestCommonAncestor(root->right, p, q);
if(left == nullptr && right == nullptr) return nullptr; // 1.
if(left == nullptr) return right; // 3.
if(right == nullptr) return left; // 4.
return root; // 2. if(left != null and right != null)
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,29 @@
/*
* File: lc_237_delete_node_in_a_linked_list_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
void deleteNode(ListNode* node) {
node->val = node->next->val;
node->next = node->next->next;
}
};
int main() {
// ======= Test Case =======
ListNode* head = vectorToLinkedList({4, 5, 1, 9});
ListNode* node = getListNode(head, 5);
// ====== Driver Code ======
Solution* slt = new Solution();
slt->deleteNode(node);
PrintUtil::printLinkedList(head);
return 0;
}

View File

@@ -0,0 +1,31 @@
/*
* File: lc_237_delete_node_in_a_linked_list_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
void deleteNode(ListNode* node) {
// 复制 node.next 到 node
node->val = node->next->val;
// 从链表中删除 node.next
node->next = node->next->next;
}
};
int main() {
// ======= Test Case =======
ListNode* head = vectorToLinkedList({4, 5, 1, 9});
ListNode* node = getListNode(head, 5);
// ====== Driver Code ======
Solution* slt = new Solution();
slt->deleteNode(node);
PrintUtil::printLinkedList(head);
return 0;
}

View File

@@ -0,0 +1,39 @@
/*
* File: lc_238_product_of_array_except_self_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int len = nums.size();
if (len == 0) return {};
vector<int> ans(len, 1);
ans[0] = 1;
int tmp = 1;
for (int i = 1; i < len; i++) {
ans[i] = ans[i - 1] * nums[i - 1];
}
for (int i = len - 2; i >= 0; i--) {
tmp *= nums[i + 1];
ans[i] *= tmp;
}
return ans;
}
};
int main() {
// ======= Test Case =======
vector<int> nums = {1, 2, 3, 4};
// ====== Driver Code ======
Solution* slt = new Solution();
vector<int> res = slt->productExceptSelf(nums);
PrintUtil::printVector(res);
return 0;
}

View File

@@ -0,0 +1,42 @@
/*
* File: lc_239_sliding_window_maximum_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
if(nums.size() == 0 || k == 0) return {};
deque<int> deque;
vector<int> res(nums.size() - k + 1);
for(int j = 0, i = 1 - k; j < nums.size(); i++, j++) {
// 删除 deque 中对应的 nums[i-1]
if(i > 0 && deque.front() == nums[i - 1])
deque.pop_front();
// 保持 deque 递减
while(!deque.empty() && deque.back() < nums[j])
deque.pop_back();
deque.push_back(nums[j]);
// 记录窗口最大值
if(i >= 0)
res[i] = deque.front();
}
return res;
}
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,45 @@
/*
* File: lc_239_sliding_window_maximum_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
if(nums.size() == 0 || k == 0) return {};
deque<int> deque;
vector<int> res(nums.size() - k + 1);
// 未形成窗口
for(int i = 0; i < k; i++) {
while(!deque.empty() && deque.back() < nums[i])
deque.pop_back();
deque.push_back(nums[i]);
}
res[0] = deque.front();
// 形成窗口后
for(int i = k; i < nums.size(); i++) {
if(deque.front() == nums[i - k])
deque.pop_front();
while(!deque.empty() && deque.back() < nums[i])
deque.pop_back();
deque.push_back(nums[i]);
res[i - k + 1] = deque.front();
}
return res;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,35 @@
/*
* File: lc_240_search_a_2d_matrix_ii_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
int i = matrix.size() - 1, j = 0;
while(i >= 0 && j < matrix[0].size())
{
if(matrix[i][j] > target) i--;
else if(matrix[i][j] < target) j++;
else return true;
}
return false;
}
};
int main() {
// ======= Test Case =======
vector<vector<int>> matrix = {{1, 4, 7, 11, 15}, {2, 5, 8, 12, 19}, {3, 6, 9, 16, 22}, {10, 13, 14, 17, 24}, {18, 21, 23, 26, 30}};
int target = 5;
// ====== Driver Code ======
Solution* slt = new Solution();
bool res = slt->searchMatrix(matrix, target);
cout << (res ? "true" : "false") << endl;
return 0;
}

View File

@@ -0,0 +1,40 @@
/*
* File: lc_242_valid_anagram_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.length() != t.length())
return false;
unordered_map<char, int> dic;
for (char c : s) {
dic[c] += 1;
}
for (char c : t) {
dic[c] -= 1;
}
for (auto kv : dic) {
if (kv.second != 0)
return false;
}
return true;
}
};
int main() {
// ======= Test Case =======
string s = "anagram", t = "nagaram";
// ====== Driver Code ======
Solution* slt = new Solution();
bool res = slt->isAnagram(s, t);
cout << (res ? "true" : "false") << endl;
return 0;
}

View File

@@ -0,0 +1,47 @@
/*
* File: lc_242_valid_anagram_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool isAnagram(string s, string t) {
// 若 s, t 长度不同,则不互为重排
if (s.length() != t.length())
return false;
// 初始化哈希表 dic
unordered_map<char, int> dic;
// 统计字符串 s 各字符数量,遇到 +1
for (char c : s) {
dic[c] += 1;
}
// 统计字符串 t 各字符数量,遇到 -1
for (char c : t) {
dic[c] -= 1;
}
// 遍历 s, t 中各字符的数量差
for (auto kv : dic) {
// 若 s, t 中某字符的数量不一致,则不互为重排
if (kv.second != 0)
return false;
}
// 所有字符数量都一致,因此互为重排
return true;
}
};
int main() {
// ======= Test Case =======
string s = "anagram", t = "nagaram";
// ====== Driver Code ======
Solution* slt = new Solution();
bool res = slt->isAnagram(s, t);
cout << (res ? "true" : "false") << endl;
return 0;
}

View File

@@ -0,0 +1,36 @@
/*
* File: lc_264_ugly_number_ii_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int nthUglyNumber(int n) {
int a = 0, b = 0, c = 0;
int res[n];
res[0] = 1;
for(int i = 1; i < n; i++) {
int n2 = res[a] * 2, n3 = res[b] * 3, n5 = res[c] * 5;
res[i] = min(min(n2, n3), n5);
if (res[i] == n2) a++;
if (res[i] == n3) b++;
if (res[i] == n5) c++;
}
return res[n - 1];
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,37 @@
/*
* File: lc_266_palindrome_permutation_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool canPermutePalindrome(string s) {
unordered_map<char, int> dic;
for (char c : s) {
dic[c] += 1;
}
int odd = 0;
for (auto kv : dic) {
if (kv.second % 2 == 1) {
if (++odd > 1)
return false;
}
}
return true;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,42 @@
/*
* File: lc_266_palindrome_permutation_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool canPermutePalindrome(string s) {
// 初始化哈希表
unordered_map<char, int> dic;
// 统计字符串中各字符的数量
for (char c : s) {
dic[c] += 1;
}
int odd = 0;
for (auto kv : dic) {
// 统计“数量为奇数”字符的个数
if (kv.second % 2 == 1) {
// 若“数量为奇数”的字符个数 > 1 ,则不是回文串排列
if (++odd > 1) // 注意 ++odd > 1 是先执行 odd 自增,再执行逻辑判断; odd++ 的顺序反之
return false;
}
}
// 若“数量为奇数”的字符个数 <= 1 ,则是回文串排列
return true;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,37 @@
/*
* File: lc_278_first_bad_version_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int firstBadVersion(int n) {
int i = 1, j = n;
while (i <= j) {
// 向下取整除法计算中点 m
int m = i + (j - i) / 2;
// 若 m 是错误版本,则最后一个正确版本一定在闭区间 [i, m - 1]
if (isBadVersion(m)) j = m - 1;
// 若 m 是正确版本,则首个错误版本一定在闭区间 [m + 1, j]
else i = m + 1;
}
// i 指向首个错误版本j 指向最后一个正确版本
return i;
}
};
int main() {
// ======= Test Case =======
// Note: You need to implement bool isBadVersion(int version) function
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->firstBadVersion(5);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,31 @@
/*
* File: lc_287_find_the_duplicate_number_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int findDuplicate(vector<int>& nums) {
unordered_map<int, bool> map;
for(int num : nums) {
if(map[num]) return num;
map[num] = true;
}
return -1;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,36 @@
/*
* File: lc_287_find_the_duplicate_number_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int i = 0;
while(i < nums.size()) {
if(nums[i] == i) {
i++;
continue;
}
if(nums[nums[i]] == nums[i])
return nums[i];
swap(nums[i],nums[nums[i]]);
}
return -1;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,45 @@
/*
* File: lc_287_find_the_duplicate_number_s3.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<int> nums;
int next(int index) {
// 直接返回当前索引处的值作为下一个索引
return nums[index];
}
int findDuplicate(vector<int>& nums) {
this->nums = nums;
int slow = 0;
int fast = 0;
// 第一次相遇
do {
slow = next(slow);
fast = next(next(fast));
} while (slow != fast);
slow = 0;
// 第二次相遇
while (slow != fast) {
slow = next(slow);
fast = next(fast);
}
return slow;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,40 @@
/*
* File: lc_295_find_median_from_data_stream_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class MedianFinder {
public:
priority_queue<int, vector<int>, greater<int>> A; // 小顶堆,保存较大的一半
priority_queue<int, vector<int>, less<int>> B; // 大顶堆,保存较小的一半
MedianFinder() { }
void addNum(int num) {
if (A.size() != B.size()) {
A.push(num);
B.push(A.top());
A.pop();
} else {
B.push(num);
A.push(B.top());
B.pop();
}
}
double findMedian() {
return A.size() != B.size() ? A.top() : (A.top() + B.top()) / 2.0;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,33 @@
/*
* File: lc_371_sum_of_two_integers_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int getSum(int a, int b) {
// 循环,当进位为 0 时跳出
while (b != 0) {
int c = (unsigned int)(a & b) << 1; // c = 进位
a ^= b; // a = 非进位和
b = c; // b = 进位
}
return a;
}
};
int main() {
// ======= Test Case =======
int a = 1, b = 2;
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->getSum(a, b);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,32 @@
/*
* File: lc_387_first_unique_character_in_a_string_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int firstUniqChar(string s) {
unordered_map<char, bool> dic;
for(char c : s)
dic[c] = dic.find(c) == dic.end();
for(int i = 0; i < s.size(); i++)
if(dic[s[i]]) return i;
return -1;
}
};
int main() {
// ======= Test Case =======
string s = "leetcode";
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->firstUniqChar(s);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,34 @@
/*
* File: lc_392_is_subsequence_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool isSubsequence(string s, string t) {
if (s.size() == 0) return true;
for (int i = 0, j = 0; j < t.size(); j++) {
if (s[i] == t[j]) {
// 若已经遍历完 s ,则提前返回 true
if (++i == s.size())
return true;
}
}
return false;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,35 @@
/*
* File: lc_3_longest_substring_without_repeating_characters_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> dic;
int i = -1, res = 0, len = s.size();
for(int j = 0; j < len; j++) {
if (dic.find(s[j]) != dic.end())
i = max(i, dic.find(s[j])->second); // 更新左指针
dic[s[j]] = j; // 哈希表记录
res = max(res, j - i); // 更新结果
}
return res;
}
};
int main() {
// ======= Test Case =======
string s = "abcabcbb";
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->lengthOfLongestSubstring(s);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,36 @@
/*
* File: lc_3_longest_substring_without_repeating_characters_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_map<char, int> dic;
int res = 0, tmp = 0, len = s.size(), i;
for(int j = 0; j < len; j++) {
if (dic.find(s[j]) == dic.end()) i = - 1;
else i = dic.find(s[j])->second; // 获取索引 i
dic[s[j]] = j; // 更新哈希表
tmp = tmp < j - i ? tmp + 1 : j - i; // dp[j - 1] -> dp[j]
res = max(res, tmp); // max(dp[j - 1], dp[j])
}
return res;
}
};
int main() {
// ======= Test Case =======
string s = "abcabcbb";
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->lengthOfLongestSubstring(s);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,29 @@
/*
* File: lc_400_nth_digit_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
int digit = 1;
long start = 1;
long count = 9;
while (n > count) { // 1.
n -= count;
start *= 10; // 1, 10, 100, ...
digit += 1; // 1, 2, 3, ...
count = digit * start * 9; // 9, 180, 2700, ...
}
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,21 @@
/*
* File: lc_400_nth_digit_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
long num = start + (n - 1) / digit;
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,22 @@
/*
* File: lc_400_nth_digit_s3.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
string s = to_string(num); // 转化为 string
int res = s[(n - 1) % digit] - '0'; // 获得 num 的 第 (n - 1) % digit 个数位,并转化为 int
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,36 @@
/*
* File: lc_400_nth_digit_s4.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int findNthDigit(int n) {
int digit = 1;
long start = 1;
long count = 9;
while (n > count) { // 1.
n -= count;
start *= 10;
digit += 1;
count = digit * start * 9;
}
long num = start + (n - 1) / digit; // 2.
return to_string(num)[(n - 1) % digit] - '0'; // 3.
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,40 @@
/*
* File: lc_409_longest_palindrome_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int longestPalindrome(string s) {
// 统计各字符数量
unordered_map<char, int> counter;
for (char c : s)
counter[c]++;
// 统计构造回文串的最大长度
int res = 0, odd = 0;
for (auto kv : counter) {
// 将当前字符出现次数向下取偶数,并计入 res
int count = kv.second;
int rem = count % 2;
res += count - rem;
// 若当前字符出现次数为奇数,则将 odd 置 1
if (rem == 1) odd = 1;
}
return res + odd;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,27 @@
/*
* File: lc_426_convert_binary_search_tree_to_sorted_doubly_linked_list_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
// 打印中序遍历
void dfs(Node* root) {
if (root == nullptr) return;
dfs(root->left); // 左
cout << root->val << endl; // 根
dfs(root->right); // 右
}
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,42 @@
/*
* File: lc_426_convert_binary_search_tree_to_sorted_doubly_linked_list_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
Node* treeToDoublyList(Node* root) {
if (root == nullptr) return nullptr;
dfs(root);
head->left = pre;
pre->right = head;
return head;
}
private:
Node *pre, *head;
void dfs(Node* cur) {
if (cur == nullptr) return;
dfs(cur->left);
if (pre != nullptr) pre->right = cur;
else head = cur;
cur->left = pre;
pre = cur;
dfs(cur->right);
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,41 @@
/*
* File: lc_46_permutations_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<vector<int>> permute(vector<int>& nums) {
dfs(nums, 0);
return res;
}
private:
vector<vector<int>> res;
void dfs(vector<int> nums, int x) {
if (x == nums.size() - 1) {
res.push_back(nums); // 添加排列方案
return;
}
for (int i = x; i < nums.size(); i++) {
swap(nums[i], nums[x]); // 交换,将 nums[i] 固定在第 x 位
dfs(nums, x + 1); // 开启固定第 x + 1 位元素
swap(nums[i], nums[x]); // 恢复交换
}
}
};
int main() {
// ======= Test Case =======
vector<int> nums = {1, 2, 3};
// ====== Driver Code ======
Solution* slt = new Solution();
vector<vector<int>> res = slt->permute(nums);
PrintUtil::printVectorMatrix(res);
return 0;
}

View File

@@ -0,0 +1,44 @@
/*
* File: lc_47_permutations_ii_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<vector<int>> permuteUnique(vector<int>& nums) {
dfs(nums, 0);
return res;
}
private:
vector<vector<int>> res;
void dfs(vector<int> nums, int x) {
if (x == nums.size() - 1) {
res.push_back(nums); // 添加排列方案
return;
}
set<int> st;
for (int i = x; i < nums.size(); i++) {
if (st.find(nums[i]) != st.end())
continue; // 重复,因此剪枝
st.insert(nums[i]);
swap(nums[i], nums[x]); // 交换,将 nums[i] 固定在第 x 位
dfs(nums, x + 1); // 开启固定第 x + 1 位元素
swap(nums[i], nums[x]); // 恢复交换
}
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,35 @@
/*
* File: lc_48_rotate_image_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
// 深拷贝 matrix -> tmp
vector<vector<int>> tmp = matrix;
// 根据元素旋转公式,遍历修改原矩阵 matrix 的各元素
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[j][n - 1 - i] = tmp[i][j];
}
}
}
};
int main() {
// ======= Test Case =======
vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// ====== Driver Code ======
Solution* slt = new Solution();
slt->rotate(matrix);
PrintUtil::printVectorMatrix(matrix);
return 0;
}

View File

@@ -0,0 +1,36 @@
/*
* File: lc_48_rotate_image_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
int n = matrix.size();
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < (n + 1) / 2; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][i];
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
matrix[j][n - 1 - i] = tmp;
}
}
}
};
int main() {
// ======= Test Case =======
vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// ====== Driver Code ======
Solution* slt = new Solution();
slt->rotate(matrix);
PrintUtil::printVectorMatrix(matrix);
return 0;
}

View File

@@ -0,0 +1,41 @@
/*
* File: lc_48_rotate_image_s3.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
void rotate(vector<vector<int>>& matrix) {
// 设矩阵行列数为 n
int n = matrix.size();
// 起始点范围为 0 <= i < n / 2 , 0 <= j < (n + 1) / 2
// 其中 '/' 为整数除法
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j < (n + 1) / 2; j++) {
// 暂存 A 至 tmp
int tmp = matrix[i][j];
// 元素旋转操作 A <- D <- C <- B <- tmp
matrix[i][j] = matrix[n - 1 - j][i];
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
matrix[j][n - 1 - i] = tmp;
}
}
}
};
int main() {
// ======= Test Case =======
vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// ====== Driver Code ======
Solution* slt = new Solution();
slt->rotate(matrix);
PrintUtil::printVectorMatrix(matrix);
return 0;
}

View File

@@ -0,0 +1,33 @@
/*
* File: lc_509_fibonacci_number_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int fib(int n) {
int a = 0, b = 1, sum;
for(int i = 0; i < n; i++){
sum = a + b;
a = b;
b = sum;
}
return a;
}
};
int main() {
// ======= Test Case =======
int n = 4;
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->fib(n);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,32 @@
/*
* File: lc_53_maximum_subarray_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int res = nums[0];
for(int i = 1; i < nums.size(); i++) {
if (nums[i - 1] > 0) nums[i] += nums[i - 1];
if (nums[i] > res) res = nums[i];
}
return res;
}
};
int main() {
// ======= Test Case =======
vector<int> nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->maxSubArray(nums);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,40 @@
/*
* File: lc_54_spiral_matrix_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.empty()) return {};
int l = 0, r = matrix[0].size() - 1, t = 0, b = matrix.size() - 1;
vector<int> res;
while (true) {
for (int i = l; i <= r; i++) res.push_back(matrix[t][i]); // left to right
if (++t > b) break;
for (int i = t; i <= b; i++) res.push_back(matrix[i][r]); // top to bottom
if (l > --r) break;
for (int i = r; i >= l; i--) res.push_back(matrix[b][i]); // right to left
if (t > --b) break;
for (int i = b; i >= t; i--) res.push_back(matrix[i][l]); // bottom to top
if (++l > r) break;
}
return res;
}
};
int main() {
// ======= Test Case =======
vector<vector<int>> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
// ====== Driver Code ======
Solution* slt = new Solution();
vector<int> res = slt->spiralOrder(matrix);
PrintUtil::printVector(res);
return 0;
}

View File

@@ -0,0 +1,50 @@
/*
* File: lc_65_valid_number_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool isNumber(string s) {
std::vector<std::unordered_map<char, int>> states = {
{ {' ', 0}, {'s', 1}, {'d', 2}, {'.', 4} }, // 0. start with 'blank'
{ {'d', 2}, {'.', 4} }, // 1. 'sign' before 'e'
{ {'d', 2}, {'.', 3}, {'e', 5}, {' ', 8} }, // 2. 'digit' before 'dot'
{ {'d', 3}, {'e', 5}, {' ', 8} }, // 3. 'digit' after 'dot'
{ {'d', 3} }, // 4. 'digit' after 'dot' (blank before 'dot')
{ {'s', 6}, {'d', 7} }, // 5. 'e'
{ {'d', 7} }, // 6. 'sign' after 'e'
{ {'d', 7}, {' ', 8} }, // 7. 'digit' after 'e'
{ {' ', 8} } // 8. end with 'blank'
};
int p = 0; // start with state 0
for (char c : s) {
char t;
if (c >= '0' && c <= '9') t = 'd'; // digit
else if (c == '+' || c == '-') t = 's'; // sign
else if (c == 'e' || c == 'E') t = 'e'; // e or E
else if (c == '.' || c == ' ') t = c; // dot, blank
else t = '?'; // unknown
if (states[p].count(t) == 0) return false;
p = states[p][t];
}
return p == 2 || p == 3 || p == 7 || p == 8;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,39 @@
/*
* File: lc_6_zigzag_conversion_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
string convert(string s, int numRows) {
if (numRows < 2)
return s;
vector<string> rows(numRows);
int i = 0, flag = -1;
for (char c : s) {
rows[i].push_back(c);
if (i == 0 || i == numRows -1)
flag = - flag;
i += flag;
}
string res;
for (const string &row : rows)
res += row;
return res;
}
};
int main() {
// ======= Test Case =======
// TODO: Add specific test case
// ====== Driver Code ======
Solution* slt = new Solution();
// TODO: Call solution method and print result
return 0;
}

View File

@@ -0,0 +1,35 @@
/*
* File: lc_704_binary_search_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int search(vector<int>& nums, int target) {
int i = 0, j = nums.size() - 1;
while (i <= j) {
int m = (i + j) / 2;
if (nums[m] < target) i = m + 1;
else if (nums[m] > target) j = m - 1;
else return m;
}
return -1;
}
};
int main() {
// ======= Test Case =======
vector<int> nums = {-1, 0, 3, 5, 9, 12};
int target = 9;
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->search(nums, target);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,33 @@
/*
* File: lc_70_climbing_stairs_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int climbStairs(int n) {
int a = 1, b = 1, sum;
for(int i = 0; i < n - 1; i++){
sum = a + b;
a = b;
b = sum;
}
return b;
}
};
int main() {
// ======= Test Case =======
int n = 2;
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->climbStairs(n);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,35 @@
/*
* File: lc_724_find_pivot_index_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
int pivotIndex(vector<int>& nums) {
int sumLeft = 0, sumRight = accumulate(nums.begin(), nums.end(), 0);
for (int i = 0; i < nums.size(); i++) {
sumRight -= nums[i];
// 若左侧元素和等于右侧元素和,返回中心下标 i
if (sumLeft == sumRight)
return i;
sumLeft += nums[i];
}
return -1;
}
};
int main() {
// ======= Test Case =======
vector<int> nums = {1, 7, 3, 6, 5, 6};
// ====== Driver Code ======
Solution* slt = new Solution();
int res = slt->pivotIndex(nums);
cout << res << endl;
return 0;
}

View File

@@ -0,0 +1,27 @@
/*
* File: lc_796_rotate_string_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool rotateString(string s, string goal) {
return s.length() == goal.length() && (goal + goal).find(s) != -1;
}
};
int main() {
// ======= Test Case =======
string s = "abcde", goal = "cdeab";
// ====== Driver Code ======
Solution* slt = new Solution();
bool res = slt->rotateString(s, goal);
cout << (res ? "true" : "false") << endl;
return 0;
}

View File

@@ -0,0 +1,46 @@
/*
* File: lc_79_word_search_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
rows = board.size();
cols = board[0].size();
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if (dfs(board, word, i, j, 0)) return true;
}
}
return false;
}
private:
int rows, cols;
bool dfs(vector<vector<char>>& board, string word, int i, int j, int k) {
if (i >= rows || i < 0 || j >= cols || j < 0 || board[i][j] != word[k]) return false;
if (k == word.size() - 1) return true;
board[i][j] = '\0';
bool res = dfs(board, word, i + 1, j, k + 1) || dfs(board, word, i - 1, j, k + 1) ||
dfs(board, word, i, j + 1, k + 1) || dfs(board, word, i , j - 1, k + 1);
board[i][j] = word[k];
return res;
}
};
int main() {
// ======= Test Case =======
vector<vector<char>> board = {{'A','B','C','E'},{'S','F','C','S'},{'A','D','E','E'}};
string word = "ABCCED";
// ====== Driver Code ======
Solution* slt = new Solution();
bool res = slt->exist(board, word);
cout << (res ? "true" : "false") << endl;
return 0;
}

View File

@@ -0,0 +1,42 @@
/*
* File: lc_86_partition_list_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode *smlDummy = new ListNode(0), *bigDummy = new ListNode(0);
ListNode *sml = smlDummy, *big = bigDummy;
while (head != nullptr) {
if (head->val < x) {
sml->next = head;
sml = sml->next;
} else {
big->next = head;
big = big->next;
}
head = head->next;
}
sml->next = bigDummy->next;
big->next = nullptr;
return smlDummy->next;
}
};
int main() {
// ======= Test Case =======
ListNode* head = vectorToLinkedList({1, 4, 3, 2, 5, 2});
int x = 3;
// ====== Driver Code ======
Solution* slt = new Solution();
ListNode* res = slt->partition(head, x);
PrintUtil::printLinkedList(res);
return 0;
}

View File

@@ -0,0 +1,47 @@
/*
* File: lc_86_partition_list_s2.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
// 新建两个链表
ListNode *smlDummy = new ListNode(0), *bigDummy = new ListNode(0);
// 遍历链表
ListNode *sml = smlDummy, *big = bigDummy;
while (head != nullptr) {
// 将 < x 的节点加入 sml 节点后
if (head->val < x) {
sml->next = head;
sml = sml->next;
// 将 >= x 的节点加入 big 节点后
} else {
big->next = head;
big = big->next;
}
head = head->next;
}
// 拼接两链表
sml->next = bigDummy->next;
big->next = nullptr;
return smlDummy->next;
}
};
int main() {
// ======= Test Case =======
ListNode* head = vectorToLinkedList({1, 4, 3, 2, 5, 2});
int x = 3;
// ====== Driver Code ======
Solution* slt = new Solution();
ListNode* res = slt->partition(head, x);
PrintUtil::printLinkedList(res);
return 0;
}

View File

@@ -0,0 +1,32 @@
/*
* File: lc_876_middle_of_the_linked_list_s1.cpp
* Created Time: 2025-12-30
* Author: krahets
*/
#include "../include/include.hpp"
// ===== Solution Code =====
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode *fast = head, *slow = head;
while (fast != nullptr && fast->next != nullptr) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
};
int main() {
// ======= Test Case =======
ListNode* head = vectorToLinkedList({1, 2, 3, 4, 5});
// ====== Driver Code ======
Solution* slt = new Solution();
ListNode* res = slt->middleNode(head);
PrintUtil::printLinkedList(res);
return 0;
}

Some files were not shown because too many files have changed in this diff Show More