模拟|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 {};

}

};

相关推荐
前端小L9 小时前
贪心算法专题(十五):借位与填充的智慧——「单调递增的数字」
javascript·算法·贪心算法
前端小L10 小时前
贪心算法专题(十四):万流归宗——「合并区间」
javascript·算法·贪心算法
hans汉斯10 小时前
基于数据重构与阈值自适应的信用卡欺诈不平衡分类模型研究
大数据·算法·机器学习·重构·分类·数据挖掘·机器人
ZPC821010 小时前
FANUC 机器人 PR 寄存器
人工智能·python·算法·机器人
yong999010 小时前
超宽带系统链路 MATLAB 仿真
开发语言·算法·matlab
历程里程碑10 小时前
LeetCode 560题:和为K子数组最优解
算法·哈希算法·散列表
qq_4017004111 小时前
C/C++中的signed char和unsigned char详解
c语言·c++·算法
leoufung11 小时前
LeetCode 67. Add Binary:从面试思路到代码细节
算法·leetcode·面试
wjykp11 小时前
79~87逻辑回归f
算法·机器学习·逻辑回归
聆风吟º11 小时前
【顺序表习题|图解|双指针】合并两个有序数组 + 训练计划 I
c语言·数据结构·c++·经验分享·算法