模拟|str_dp

lc2405

hash

class Solution {

public:

int partitionString(string s)

{

unordered_set<char> set;

int ret = 0;

for(auto& c : s)

{

++if(set.count(c))++

{

ret++;

set.clear();

}

set.insert(c);

}

++ret += 1;//last++

return ret;

}

};

mask位运算优化set

++if(mask & (1 << bit))++ // 查1

++mask |= (1 << bit); //置1++

class Solution {

public:

int partitionString(string s)

{

int mask = 0; // 用二进制位标记字符是否出现:第i位为1表示'a'+i已存在

int ret = 0;

for(auto& c : s)

{

int bit = c - 'a';

++if(mask & (1 << bit))++ // 查1

{

ret += 1;

mask = 0; // 重置mask

}

++mask |= (1 << bit); //置1++

}

ret += 1;

return ret;

}

};

lc3531

预处理统计每个x行的y最值、y列的x最值

若建筑的x、y都在对应行列最值中间,就是被覆盖的,计数返回。

class Solution {

public:

int countCoveredBuildings(int n, vector<vector<int>>& buildings)

{

//++预处理 行位置极值和列位置极值++

unordered_map<int,int> row_min,row_max;

unordered_map<int,int> col_min,col_max;

for(auto& b:buildings)

{

int x = b[0], y = b[1];

// 预处理行极值

if (!row_min.count(x) || y < row_min[x]) row_min[x] = y;

if (!row_max.count(x) || y > row_max[x]) row_max[x] = y;

// 预处理列极值

if (!col_min.count(y) || x < col_min[y]) col_min[y] = x;

if (!col_max.count(y) || x > col_max[y]) col_max[y] = x;

}

int ans=0;

for(auto& b:buildings)

{

int x=b[0],y=b[1];

bool up=(y<row_max[x]);

bool down=(y>row_min[x]);

bool left=(x>col_min[y]);

bool right=(x<col_max[y]);

++if(up && down && left && right) ans++;++

}

return ans;

}

};

lc16.21

找到去掉差值的一半

class Solution {

/*

输入:array1 = [4, 1, 2, 1, 1, 2], array2 = [3, 6, 3, 3]

输出:[1, 3]

*/

public:

vector<int> findSwapValues(vector<int>& array1, vector<int>& array2)

{

unordered_map<int,int> hash;

int sum1=0,sum2=0;

int m=array1.size(),n=array2.size();

for(int i=0;i<n;i++)

{

int a=array2[i];

sum2+=a;

hash[a]=i;;

}

for(auto& a:array1)

sum1+=a;

int d=sum1-sum2;

if(d%2) return {};

for(int i=0;i<m;i++)

{

int a=array1[i];

++int f=a-d/2;
if(hash.count(f))
++

return {a,f};

}

return {};

}

};

相关推荐
前端小L2 小时前
回溯算法专题(九):棋盘上的巅峰对决——经典「N 皇后」问题
数据结构·算法
DR-ZF-2 小时前
20251210 线性最小二乘法迭代拟合(梯度下降)
算法·机器学习·最小二乘法
神仙别闹2 小时前
基于C++生成树思想的迷宫生成算法
开发语言·c++·算法
CoovallyAIHub2 小时前
南京理工大学联手百度、商汤科技等团队推出Artemis:用结构化视觉推理革新多模态感知
深度学习·算法·计算机视觉
天才少女爱迪生2 小时前
图像序列预测有什么算法方案
人工智能·python·深度学习·算法
cici158742 小时前
3D有限元直流电阻率法正演程序
算法·3d
黑色的山岗在沉睡2 小时前
滤波算法数学前置——线性化
线性代数·算法
t198751282 小时前
火电机组热经济性分析MATLAB程序实现
人工智能·算法·matlab
Hello娃的3 小时前
【半导体】肖特基接触AND欧姆接触
人工智能·算法