leetcode竞赛:85 场双周赛

编程入门 行业动态 更新时间:2024-10-25 22:30:22

leetcode竞赛:85 场<a href=https://www.elefans.com/category/jswz/34/1722555.html style=双周赛"/>

leetcode竞赛:85 场双周赛

链接:/
日期:2022年08月20日
1.
定长滑动窗口

class Solution {
public:int minimumRecolors(string blocks, int k) {int n = blocks.size(), cnt = 0, res = 1000;for (int i = 0, j = 0; i < n; i++) {while (j < n && j - i < k) {if (blocks[j++] == 'W') cnt++;}if (j - i == k) res = min(res, cnt);if (blocks[i] == 'W') cnt--;}return res;}
};

暴力模拟

class Solution {
public:int secondsToRemoveOccurrences(string s) {int res = 0, n = s.size();while (true) {int flag = 0;for (int i = 1; i < n; i++) {if (s[i - 1] == '0' && s[i] == '1') {swap(s[i-1], s[i]);i++;flag = 1;}}if (!flag) break;res++;}return res;}
};

差分算法

class Solution {
public:string shiftingLetters(string s, vector<vector<int>>& shifts) {int n = s.size();vector<int> t(n + 1);for (auto &p:shifts) {int a = p[0], b = p[1], d = p[2];if (d == 0) d = -1;t[a] += d;t[b + 1] -= d;}for (int i = 1; i <= n; i++) {t[i] += t[i - 1];t[i - 1] = t[i - 1] % 26 + 26;char c = (s[i - 1] - 'a' + t[i - 1]) % 26 + 'a';s[i - 1] = c;}return s;}
};

逆向并查集 做法

class Solution {
public:typedef long long LL;vector<LL> s;vector<int> p;int find(int x) {if (p[x] != x) {p[x] = find(p[x]);}return p[x];}LL Union(int a, int b) {a = find(a), b = find(b);p[a] = b;s[b] += s[a];return s[b];}vector<long long> maximumSegmentSum(vector<int>& nums, vector<int>& removeQueries) {vector<LL> res;int n = removeQueries.size();for (int i = 0; i < nums.size(); i++) {p.push_back(i);s.push_back(0);}LL mx = 0;for (int i = n - 1; i >= 0; i--) {res.push_back(mx);int x = removeQueries[i];s[x] = nums[x];if (x > 0 && s[x - 1]) mx = max(mx, Union(x, x - 1));if (x < n - 1 && s[x + 1]) mx = max(mx, Union(x, x + 1));mx = max(mx, s[x]);}reverse(res.begin(), res.end());return res;}
};

模拟列项正向维护分裂数组的最大值:二分,lower_bound

class Solution {
public:typedef long long LL;vector<long long> maximumSegmentSum(vector<int>& nums, vector<int>& removeQueries) {int n = nums.size();vector<LL> f(n + 1), res;for (int i = 0; i < n; i++) {f[i + 1] = f[i] + nums[i];}set<int> st; st.insert(0); st.insert(n);multiset<long long> ms;ms.insert(f[n]);for (int pos : removeQueries) {auto i = st.upper_bound(pos);auto j = (i--);int L = *i, R = *j;ms.erase(ms.lower_bound(f[R] - f[L]));st.insert(pos);st.insert(pos + 1);ms.insert(f[pos] - f[L]);ms.insert(f[R] - f[pos + 1]);res.push_back(*ms.rbegin());}return res;}
};

更多推荐

leetcode竞赛:85 场双周赛

本文发布于:2023-12-06 16:56:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1668222.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:双周   leetcode

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!