【每日算法Day 77】LeetCode 第 181 场周赛题解

网友投稿 284 2022-12-02

【每日算法Day 77】LeetCode 第 181 场周赛题解

周赛链接

​​leetcode-cn.com/contest /weekly-contest-181 ​​

LeetCode 5364. 按既定顺序创建目标数组

题目链接

​​leetcode-cn.com/problem s/create-target-array-in-the-given-order/ ​​

题解

c++ ​​vector​​​ 自带 ​​insert​​ 函数,直接用就行了。

代码(c++)

class Solution {public: vector createTargetArray(vector& nums, vector& index) { int n = nums.size(); vector target; for (int i = 0; i < n; ++i) { target.insert(target.begin()+index[i], nums[i]); } return target; }};

LeetCode 5178. 四因数

题目链接

​​leetcode-cn.com/problem s/four-divisors/ ​​

代码(c++)

class Solution {public: int sumFourDivisors(vector& nums) { int res = 0; for (auto x : nums) { int cnt = 0, sum = 0; for (int i = 1; i*i <= x; ++i) { if (i*i == x) { cnt++; break; } if (x%i == 0) { cnt += 2; sum += i + x/i; } if (cnt > 4) break; } if (cnt == 4) res += sum; } return res; }};

LeetCode 5366. 检查网格中是否存在有效路径

题目链接

​​leetcode-cn.com/problem s/check-if-there-is-a-valid-path-in-a-grid/ ​​

代码(c++)

class Solution {public: int link(int a, int b, int d) { if (d == 1 || d == 3) { d--; swap(a, b); } if (d == 0) return (a==1||a==4||a==6)&&(b==1||b==3||b==5); if (d == 2) return (a==2||a==3||a==4)&&(b==2||b==5||b==6); return false; } bool hasValidPath(vector>& grid) { int n = grid.size(), m = grid[0].size(); int dx[4] = {0, 0, 1, -1}; int dy[4] = {1, -1, 0, 0}; vector> vis(n, vector(m, 0)); queue> Q; Q.push({0, 0}); vis[0][0] = 1; while (!Q.empty()) { pair p = Q.front(); Q.pop(); int x = p.first, y = p.second; if (x == n-1 && y == m-1) return true; for (int i = 0; i < 4; ++i) { int nx = x + dx[i], ny = y + dy[i]; if (0 <= nx && nx < n && 0 <= ny && ny < m && !vis[nx][ny] && link(grid[x][y], grid[nx][ny], i)) { vis[nx][ny] = 1; Q.push({nx, ny}); } } } return false; }};

LeetCode 5367. 最长快乐前缀

题目链接

​​leetcode-cn.com/problem s/longest-happy-prefix/ ​​

代码(c++)

class Solution {public: void getNext(string s, vector& next) { int n = s.size(); next[0] = 0; for (int q = 1, k = 0; q < n; ++q) { while (k > 0 && s[q] != s[k]) k = next[k-1]; if (s[q] == s[k]) k++; next[q] = k; } } string longestPrefix(string s) { int n = s.size(); vector next(n); getNext(s, next); return s.substr(0, next[n-1]); }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Vue.js 模板语法
下一篇:Java框架解说之BIO NIO AIO不同IO模型演进之路
相关文章

 发表评论

暂时没有评论,来抢沙发吧~