leetcode 单:
第一题https://leetcode.cn/problems/smallest-even-multiple/
class Solution {
public:
int smallestEvenMultiple(int n) {
if(n & 1){
return 2 * n;
}else return n;
}
};
第二题https://leetcode.cn/problems/length-of-the-longest-alphabetical-continuous-substring/
双指针,[j, i]
, 满足连续字符串的条件, 双指针i++
; 不满足连续字符串, j = i
;
class Solution {
public:
int longestContinuousSubstring(string s) {
int len = 1;
int j = 0;
for(int i = 1; i < s.size(); i ++){
if(s[i] != s[j] + i - j){
j = i;
}
len = max(len, i - j + 1);
}
return len;
}
};
第三题https://leetcode.cn/problems/reverse-odd-levels-of-binary-tree/
对于奇数层,直接交换层里面的所有元素值,通过同时递归左右子树实现。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* left, TreeNode* right, int res){
if(left == nullptr && right == nullptr) return ;
if(res & 1){
int zhon = left -> val;
left -> val = right -> val;
right -> val = zhon;
}
dfs(left -> left, right -> right, res + 1);
dfs(left -> right, right -> left, res + 1);
}
TreeNode* reverseOddLevels(TreeNode* root) {
dfs(root -> left, root -> right, 1);
return root;
}
};
leetcode 双:
第一题https://leetcode.cn/problems/count-days-spent-together/
将字符串日期转为整型的某一天,求两个区间的交集即可
class Solution {
public:
int countDaysTogether(string arriveAlice, string leaveAlice, string arriveBob, string leaveBob) {
int day1 = calc(arriveAlice);
int day2 = calc(leaveAlice);
int day3 = calc(arriveBob);
int day4 = calc(leaveBob);
return max(min(day2, day4) - max(day1, day3) + 1, 0);
}
int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int calc(string s) {
int m = (s[0] - '0') * 10 + s[1] - '0';
int ans = (s[3] - '0') * 10 + s[4] - '0';
for (int i = 1; i < m; i++) {
ans += days[i - 1];
}
return ans;
}
};
第二题https://leetcode.cn/problems/maximum-matching-of-players-with-trainers/
用优先队列来做的,依次比较两队头即可
class Solution {
public:
int matchPlayersAndTrainers(vector<int>& players, vector<int>& trainers) {
priority_queue<int, vector<int>, less<>> a, b;
for(auto c : players) a.push(c);
for(auto c : trainers) b.push(c);
int count = 0;
while(!a.empty() && !b.empty()){
if(a.top() > b.top()){
a.pop();
}else{
a.pop(), b.pop();
count ++;
}
}
return count;
}
};
第三题https://leetcode.cn/problems/smallest-subarrays-with-maximum-bitwise-or/
从后往前遍历数组, 定义pos[i][j]表示: 从当前位置i开始往后数组元素值, 第j位为1的最近位置; pos[i][j]初始化为-1, 当(nums[i]>>j) & 1 == 1, pos[i][j] = i; 否则pos[i][j] = pos[i + 1][j]
实际实现时, 二维压缩为一维
class Solution {
public:
vector<int> smallestSubarrays(vector<int>& nums) {
int n = nums.size();
vector<int> pos(32, -1);
vector<int> ans(n);
for (int i = n - 1; i >= 0; i--) {
int mx = 1;
for (int j = 0; j < 31; j++) {
if ((nums[i] >> j) & 1) {
pos[j] = i;
} else {
mx = max(mx, pos[j] - i + 1);
}
}
ans[i] = mx;
}
return ans;
}
};