hash滑窗|dp

lcr107

多源bfs

注意init ret -1防重复入队

++if(x>=0 && x<m && y>=0 && y<n && ret[x][y] == -1)
// 最近距离 = 相邻0的距离 + 1
ret[x][y] = ret[a][b] + 1;
++

class Solution {

typedef pair<int,int> pii;

int dx[4]={0,0,1,-1};

int dy[4]={1,-1,0,0};

public:

vector<vector<int>> updateMatrix(vector<vector<int>>& mat)

{

queue<pii> q;

int m=mat.size(),n=mat[0].size();

vector<vector<int>> ret(m,vector<int>(n,0));

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

{

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

{

if(mat[i][j]==0)

{

q.push({i,j});

}

else

{

// 标记未处理的1为-1

ret[i][j] = -1;

}

}

}

while(!q.empty())

{

auto [a,b] = q.front();

q.pop();

for(int k=0;k<4;k++)

{

int x=a+dx[k],y=b+dy[k];

++if(x>=0 && x<m && y>=0 && y<n && ret[x][y] == -1)
{
// 最近距离 = 相邻0的距离 + 1
ret[x][y] = ret[a][b] + 1;
++

q.push({x,y});

}

}

}

return ret;

}

};

lcr17

滑动窗口+两个哈希表

在s里找包含t所有字符的最短子串,找不到就返回空

class Solution {

public:

string minWindow(string s, string t) {

unordered_map<char, int> tag;

unordered_map<char, int> hash;

for (char c : t) {

tag[c]++;

}

int cnt = 0;

int tcnt = t.size();

int l = 0, r = 0;

int minLen = INT_MAX;

int start = 0;

int n = s.size();

while (r < n) {

char c = s[r];

hash[c]++;

if (hash[c] <= tag[c]) {

cnt++;

}

r++;

while (cnt == tcnt)

{

++if (r - l < minLen) {++

++minLen = r - l;++

++start = l;++

}

char leftChar = s[l];

++hash[leftChar]--;++

++if (hash[leftChar] < tag[leftChar])++

++cnt--;++

l++;

}

}

return minLen == INT_MAX ? "" : s.substr(start, minLen);

}

};

lc1186

class Solution {

public:

int maximumSum(vector<int>& arr) {

int n=arr.size();

bool flag=false;

int maxNum=INT_MIN;

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

if(arr[i]>0){

flag=true;

break;

}

maxNum=max(maxNum,arr[i]);

}

if(flag==false)return maxNum;

vector<int>pre(n+2),nex(n+2);

int add=0;

for(int i=1;i<=n;i++){

add+=arr[i-1];

++if(add<arr[i-1]) add=arr[i-1];++

++pre[i]=add>0?add:0;++

}

add=0;

for(int i=n;i>=1;i--){

add+=arr[i-1];

if(add<arr[i-1])add=arr[i-1];

nex[i]=add>0?add:0;

}

int ans=INT_MIN;

for(int i=1;i<=n;i++){

++ans=max(max(ans,pre[i-1]+nex[i+1]+arr[i-1]),pre[i-1]+nex[i+1]);++

}

return ans;

}

};

相关推荐
Tingjct9 分钟前
【初阶数据结构-二叉树】
c语言·开发语言·数据结构·算法
C雨后彩虹10 分钟前
计算疫情扩散时间
java·数据结构·算法·华为·面试
yyy(十一月限定版)1 小时前
寒假集训4——二分排序
算法
星火开发设计1 小时前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识
醉颜凉1 小时前
【LeetCode】打家劫舍III
c语言·算法·leetcode·树 深度优先搜索·动态规划 二叉树
达文汐1 小时前
【困难】力扣算法题解析LeetCode332:重新安排行程
java·数据结构·经验分享·算法·leetcode·力扣
一匹电信狗1 小时前
【LeetCode_21】合并两个有序链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
User_芊芊君子1 小时前
【LeetCode经典题解】搞定二叉树最近公共祖先:递归法+栈存路径法,附代码实现
算法·leetcode·职场和发展
算法_小学生1 小时前
LeetCode 热题 100(分享最简单易懂的Python代码!)
python·算法·leetcode
执着2591 小时前
力扣hot100 - 234、回文链表
算法·leetcode·链表