剑指 Offer 07. 重建二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
unordered_map<int, int> pos;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
for (int i = 0; i < n; i ++ ) {
pos[inorder[i]] = i;
}
return build(preorder, 0, n - 1, 0, n - 1);
}
TreeNode* build(vector<int>&preorder, int pl, int pr, int il, int ir) {
if (pl > pr) return NULL;
auto root = new TreeNode(preorder[pl]);
int k = pos[root->val];
root->left = build(preorder, pl + 1, pl + k - il, il, k - 1);
root->right = build(preorder, pl + k - il + 1, pr, k + 1, ir);
return root;
}
};
剑指 Offer 14- I. 剪绳子
思路:找规律
草稿纸上写出前10个数,发现拆分的数一定是2或者3乘积最大的,考虑 n n%3 n余数是几,分情况讨论
class Solution {
public:
int integerBreak(int n) {
if (n <= 3) return n - 1;
else if (n == 4) return 4;
else {
if (n % 3 == 0) return pow(3, n / 3);
else if (n % 3 == 1) return pow(3, n / 3 - 1) * 4;
else return pow(3, n / 3) * 2;
}
}
};
剑指 Offer 14- II. 剪绳子 II
与剪绳子类似,但是因为数字很大,所以使用 p o w pow pow比较慢,并且可能会超 l o n g l o n g longlong longlong,所以手写 q u i c k p o w quick_pow quickpow函数,并且每一次都要%1e9+7
class Solution {
public:
const int mod = 1e9 + 7;
int cuttingRope(int n) {
if (n <= 3) return n - 1;
else {
if (n % 3 == 0) return quick_pow(3, n / 3);
else if (n % 3 == 1) return quick_pow(3, n / 3 - 1) * 4 % mod;
else return quick_pow(3, n / 3) * 2 % mod;
}
}
long long quick_pow(long long a, int b) {
long long res = 1;
while (b) {
if (b & 1) {
res = res * a % mod;
b -- ;
}
else {
a = a * a % mod;
b >>= 1;
}
}
return res;
}
};
剑指 Offer 25. 合并两个排序的链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
auto dummy = new ListNode(-1), cur = dummy;
dummy->next = NULL;
while (l1 && l2) {
if (l1->val < l2->val) {
cur = cur->next = l1;
l1 = l1->next;
}
else {
cur = cur->next = l2;
l2 = l2->next;
}
}
while (l1) {
cur = cur->next = l1;
l1 = l1->next;
}
while (l2) {
cur = cur->next = l2;
l2 = l2->next;
}
return dummy->next;
}
};
剑指 Offer 26. 树的子结构
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSubStructure(TreeNode* A, TreeNode* B) {
if (!A || !B) return false;
if (ispart(A, B)) return true;
return isSubStructure(A->left, B) || isSubStructure(A->right, B);
}
bool ispart(TreeNode* a, TreeNode* b) {
if (!b) return true;
if (!a || a->val != b->val) return false;
return ispart(a->left, b->left) && ispart(a->right, b->right);
}
};