week30
292 - Nim游戏
class Solution {
public:
bool canWinNim(int n) {
return n % 4;
}
};295 - 数据流的中位数
297 - 二叉树的序列化与反序列化
299 - 猜数字游戏
300 - 最长递增子序列
Last updated
class Solution {
public:
bool canWinNim(int n) {
return n % 4;
}
};Last updated
class MedianFinder {
public:
priority_queue<int, vector<int>, greater<int>> up;
priority_queue<int> down;
// 保证down的元素 和up相等或者只多1
public:
/** initialize your data structure here. */
MedianFinder() = default;
void addNum(int num) {
if(down.empty() || num <= down.top())
{
down.push(num);
if(down.size() > up.size() + 1)
{
up.push(down.top());
down.pop();
}
}
else
{
up.push(num);
if(up.size() > down.size())
{
down.push(up.top());
up.pop();
}
}
}
double findMedian() {
if((down.size() + up.size()) % 2) return down.top();
else return (down.top() + up.top()) / 2.0;
}
};class Codec {
public:
string path;
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
dfs_s(root);
return path;
}
void dfs_s(TreeNode* root)
{
if(root == nullptr) path += "#,";
else
{
path += to_string(root->val) + ',';
dfs_s(root->left);
dfs_s(root->right);
}
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
int u = 0;
return dfs_d(data, u);
}
TreeNode* dfs_d(string& data, int& u) // ! 注意这里哦
{
if(data[u] == '#')
{
u += 2;
return nullptr;
}
else
{
int k = u;
while(data[u] != ',') u++;
TreeNode* root = new TreeNode(stoi(data.substr(k, u - k)));
u++; // 跳过逗号
root->left = dfs_d(data, u);
root->right = dfs_d(data, u);
return root;
}
}
};class Solution {
public:
string getHint(string secret, string guess) {
int a = 0, b = 0;
vector<int> shash(11, 0), ghash(11, 0);
for(int i = 0; i < secret.size(); i++)
{
shash[secret[i] - '0']++;
ghash[guess[i] - '0']++;
if(secret[i] == guess[i]) a++;
}
for(int i = 0; i < 10; i++)
b += min(shash[i], ghash[i]);
return to_string(a) + "A" + to_string(b - a) + "B";
}
};class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
vector<int> f(n + 1, 1);
int res = 1;
for(int i = 0; i < n; i++)
for(int j = 0; j < i; j++)
{
if(nums[i] > nums[j])
{
f[i] = max(f[i], f[j] + 1);
res = max(res, f[i]);
}
}
return res;
}
};for(int i = 1; i <= n; i++)
{
f[i] = 0;
g[i] = 0;
for(int j = 1; j < i; j ++)
{
if(a[j] < a[i])
{
if(f[i] < f[j] + 1)
{
f[i] = f[j] + 1;
g[i] = j;
}
}
}
}
int k = 1;
for(int i = 1; i <= n; i++)
if(f[k] < f[i])
k = i;
for(int i = 0, len = f[k]; i < len; i++)
{
printf("%d ", a[k]);
k = g[k];
} f[cnt++] = w[0];
for (int i = 1; i < n; i++) {
if (w[i] > f[cnt-1]) f[cnt++] = w[i];
else {
int l = 0, r = cnt - 1;
while (l < r) {
int mid = (l + r) >> 1;
if (f[mid] >= w[i]) r = mid;
else l = mid + 1;
}
f[r] = w[i];
}
}
cout << cnt << endl;