周末快乐。今天周赛前两题都比较基础,直接模拟就行;第三题需要抽象想一下,能想到这是一个BFS求最短路的问题的话就没什么问题了,代码挺好实现的;第四题动态规划,和编辑距离的dp类型类似。



这题还是蛮基础的,不需要什么思考量,一趟模拟对比就行了。
class Solution {public:int smallestEqual(vector<int>& nums) {for(int i = 0; i < nums.size(); i ++)if( i % 10 == nums[i]) return i;return -1;}};



直接模拟,由于链表是顺序访问的,每次找到的局部最大最小值位置都是严格单调递增的,最小的最先找到,最大的最后找到,而距离最近的则每找到一个就与前面对比一下,记录最小距离就行。
class Solution {public:int minn = 100010 , mind = 100010;vector<int> nodesBetweenCriticalPoints(ListNode* head) {int cnt = 0 , location = 1;vector<int> ans(2,-1);vector<int> nums;ListNode* front = head;head=head->next;int last=-1;while(head != nullptr && head->next != nullptr){location ++;if(head->val > head->next->val && head->val > front->val){//局部极大cnt ++;if(cnt == 1) {minn = location;last = location;}elsemind = min(mind , location - last);last = location;}else if(head->val < head->next->val && head->val < front->val){//局部极小cnt ++;if(cnt == 1) {minn = location;last = location;}elsemind = min(mind , location - last);last = location;}front = head;head = head->next;}if(cnt < 2)return ans;else{ans[1] = last - minn;ans[0] = mind;return ans;}}};
5916. 转化数字的最小运算数



这题就需要稍微抽象一下,用BFS(广度优先)求最短路来解。start是源点,goal则是目标,nums每个数的每一次操作相当于移动一步将源数改变成了另一种状态,广度优先遍历找到到达goal的最短路,到不了goal就返回-1。
class Solution {public:int minimumOperations(vector<int>& nums, int st, int goal) {vector<int> dist(1010,-1);queue<int> q;q.push(st);dist[st] = 0;while(!q.empty()){int f = q.front();q.pop();for(auto &x : nums){int t;t = f + x;if(t == goal) return dist[f] + 1;if(t >= 0 && t <= 1000 && dist[t] == -1){q.push(t);dist[t] = dist[f] + 1;}t = f - x;if(t == goal) return dist[f] + 1;if(t >= 0 && t <= 1000 && dist[t] == -1){q.push(t);dist[t] = dist[f] + 1;}t = f ^ x;if(t == goal) return dist[f] + 1;if(t >= 0 && t <= 1000 && dist[t] == -1){q.push(t);dist[t] = dist[f] + 1;}}}return -1;}};
5917. 同源字符串检测



dp。用dp[i][j]记录下,s1的前 i 个字符与s2的前 j 个字符匹配的情况下,剩下的通配符数量。通配符是什么意思?这是由于字符串中的数字带来的,比如数字3,表示长度为3的任意串,于是这三个位置就可以放任何字符,可以理解为通配符。如果通配符数量大于0,表示,s1的前i个字符与s2的前j个字符匹配,s1还剩下一些余量,小于0,则表示s2剩余了一些位置可以放字符,等于0则表示刚好匹配。
class Solution {public:bool isdigit(char ch){return (ch >= '0' && ch <= '9');}bool possiblyEquals(string s1, string s2) {int n = s1.size() , m = s2.size();vector<vector<unordered_set<int>>> dp(n + 1 , vector<unordered_set<int>>(m + 1));dp[0][0].insert(0);for(int i = 0; i <= n; i ++){for(int j = 0; j <= m; j ++){for(auto &x : dp[i][j]){int num = 0;for(int k = i; k < min(n , i + 3); k ++){if(isdigit(s1[k])){num = num * 10 + s1[k] - '0';dp[k + 1][j].insert(x + num);}else{break;}}num = 0;for(int k = j; k < min(j + 3 , m); k ++){if(isdigit(s2[k])){num = num * 10 + s2[k] - '0';dp[i][k + 1].insert(x - num);}else{break;}}if(i < n && !isdigit(s1[i]) && x < 0){dp[i + 1][j].insert(x + 1);}if(j < m && !isdigit(s2[j]) && x > 0)dp[i][j + 1].insert(x - 1);if(i < n && j < m && x == 0 && s1[i] == s2[j])dp[i + 1][j + 1].insert(0);}}}return dp[n][m].count(0);}};
文章转载自fighting小王子,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




