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";

}

};

相关推荐
sali-tec12 分钟前
C# 基于halcon的视觉工作流-章66 四目匹配
开发语言·人工智能·数码相机·算法·计算机视觉·c#
小明说Java18 分钟前
常见排序算法的实现
数据结构·算法·排序算法
行云流水20191 小时前
编程竞赛算法选择:理解时间复杂度提升解题效率
算法
smj2302_796826523 小时前
解决leetcode第3768题.固定长度子数组中的最小逆序对数目
python·算法·leetcode
cynicme3 小时前
力扣3531——统计被覆盖的建筑
算法·leetcode
core5124 小时前
深度解析DeepSeek-R1中GRPO强化学习算法
人工智能·算法·机器学习·deepseek·grpo
mit6.8244 小时前
计数if|
算法
a伊雪4 小时前
c++ 引用参数
c++·算法
Data_agent5 小时前
1688获得1688店铺列表API,python请求示例
开发语言·python·算法
2301_764441335 小时前
使用python构建的应急物资代储博弈模型
开发语言·python·算法