hash|快速幂|栈

lc1372

(DFS)遍历二叉树,分别从根节点开始尝试向左、向右的 zigzag 路径

记录最长路径长度并返回

sum: 题目加条件,代码dfs就可以加参数...

class Solution {

public:

int longestZigZag(TreeNode* root) {

int ans=0;

function<void(TreeNode*,int,int)>dfs=\&(TreeNode* root,int sum,int dire)

{

if(!root){

ans=max(ans,sum);

return ;

}

if(dire==0){

dfs(root->left,sum+1,1);

dfs(root->right,1,0);

}

else{

dfs(root->right,sum+1,0);

dfs(root->left,1,1);

}

};

dfs(root,0,0);

dfs(root,0,1);

return ans-1;

}

};

lc769

class Solution {

public:

int maxChunksToSorted(vector<int>& arr) {

int ans = 0, mx = 0;

for (int i = 0; i < arr.size(); ++i) {

mx = max(mx, arri);

ans += i == mx;

}

return ans;

}

};

lc768

! 单增栈的大小即为答案

class Solution {

public:

int maxChunksToSorted(vector<int>& arr) {

stack<int> stk;

for (int& v : arr) {

if (stk.empty() || stk.top() <= v)

stk.push(v);

else {

int mx = stk.top();

stk.pop();

while (!stk.empty() && stk.top() > v) stk.pop();

stk.push(mx);

}

}

return stk.size();

}

};

lc388

记录各层级目录长度,遍历输入字符串,找出包含后缀的文件的最长路径长度

class Solution {

public:

int lengthLongestPath(string input) {

int n = input.size();

int res = 0;

vector<int> sum(1000);

int p = 0;

while (p < n) {

int level = 0;

while (p < n && inputp == '\t') {

level++;

p++;

}

int q = p;

bool isfile = false;

while (p < n && inputp != '\n') {

if (inputp == '.')

isfile = true;

p++;

}

if (isfile) {

res = max(res, sumlevel + p - q);

} else {

sumlevel + 1 = sumlevel + p - q + 1;

}

p++;

}

return res;

}

};

lc372_递归 分治 super_pow

快速幂_倍增

用快速幂结合递归,计算a的由数组b表示的幂对1337取模的结果

class Solution {

public:

int MOD = 1337;

int qp(int a, int b) {

a %= MOD;

int t = 1;

while(b) {

if (b%2 == 1) {

t *= a;

t %= MOD;

}

a *= a;

a %= MOD;

b >>= 1;

}

return t;

}

int superPow(int a, vector<int>& b) {

if (b.size() == 0) return 1;

int p = b.back();

b.pop_back();

return qp(superPow(a, b), 10) * qp(a, p) % MOD;

}

};

lc2347

hash

class Solution {

public:

string bestHand(vector<int>& ranks, vector<char>& suits)

{

++bool flush = true;++

for (int i = 1; i < 5 && flush; ++i) {

flush = suitsi == suitsi - 1;

}

if (flush) {

return "Flush";

}

int cnt14{};

bool pair = false;

for (int& x : ranks)

{

if (++cntx == 3)

return "Three of a Kind";

pair |= cntx == 2;

}

return pair ? "Pair" : "High Card";

}

};

相关推荐
折哥的程序人生 · 物流技术专研3 小时前
Java面试85题图解版 · 特别篇:2026后端高频面试题复盘(算法底层逻辑+高并发架构设计全解析,附Java实战代码)
java·网络·数据库·算法·面试
想吃火锅10054 小时前
【leetcode】14.最长公共前缀js
算法·leetcode·职场和发展
云絮.6 小时前
数据库操作
数据库·mysql·算法·oracle
小林ixn6 小时前
LeetCode 206. 反转链表(迭代 + 递归详解)
算法·leetcode·链表
凡人叶枫6 小时前
Effective C++ 条款17:以独立语句将 newed 对象置入智能指针
java·linux·开发语言·c++·算法
菜鸟‍7 小时前
LeetCode 1 27 和 704 || 两数之和 移除元素 二分查找
算法·leetcode·职场和发展
退休倒计时9 小时前
【每日一题】LeetCode 142. 环形链表 II TypeScript
算法·leetcode·链表·typescript
popcorn_min9 小时前
Digits 手写数字识别:随机森林多分类 + 像素级特征热力图
算法·随机森林·分类
liulilittle10 小时前
拥塞控制:排水终止的两种决策:OR 与 AND
网络·tcp/ip·计算机网络·算法·信息与通信·tcp·通信
weixin_3077791310 小时前
从脚本执行到智能体协作:AI辅助测试能力的范式重构
运维·开发语言·人工智能·算法·测试用例