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, arr[i]);

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 && input[p] == '\t') {

level++;

p++;

}

int q = p;

bool isfile = false;

while (p < n && input[p] != '\n') {

if (input[p] == '.')

isfile = true;

p++;

}

if (isfile) {

res = max(res, sum[level] + p - q);

} else {

sum[level + 1] = sum[level] + 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 = suits[i] == suits[i - 1];

}

if (flush) {

return "Flush";

}

int cnt[14]{};

bool pair = false;

for (int& x : ranks)

{

if (++cnt[x] == 3)

return "Three of a Kind";

pair |= cnt[x] == 2;

}

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

}

};

相关推荐
Gorway3 小时前
解析残差网络 (ResNet)
算法
拖拉斯旋风3 小时前
LeetCode 经典算法题解析:优先队列与广度优先搜索的巧妙应用
算法
Wect3 小时前
LeetCode 207. 课程表:两种解法(BFS+DFS)详细解析
前端·算法·typescript
灵感__idea17 小时前
Hello 算法:众里寻她千“百度”
前端·javascript·算法
Wect1 天前
LeetCode 130. 被围绕的区域:两种解法详解(BFS/DFS)
前端·算法·typescript
NAGNIP2 天前
一文搞懂深度学习中的通用逼近定理!
人工智能·算法·面试
颜酱2 天前
单调栈:从模板到实战
javascript·后端·算法
CoovallyAIHub2 天前
仿生学突破:SILD模型如何让无人机在电力线迷宫中发现“隐形威胁”
深度学习·算法·计算机视觉
CoovallyAIHub2 天前
从春晚机器人到零样本革命:YOLO26-Pose姿态估计实战指南
深度学习·算法·计算机视觉
CoovallyAIHub2 天前
Le-DETR:省80%预训练数据,这个实时检测Transformer刷新SOTA|Georgia Tech & 北交大
深度学习·算法·计算机视觉