1 温度转换
温度转换
Solution
class Solution {
public:
vector<double> convertTemperature(double celsius) {
double kelvin = celsius + 273.15;
double fahrenheit = celsius * 1.80 + 32.00;
vector<double> ans;
ans.push_back(kelvin);
ans.push_back(fahrenheit);
return ans;
}
};
2 最小公倍数为 K 的子数组数目
最小公倍数为 K 的子数组数目
Solution
class Solution {
public:
long long gcd(long long a,long long b)
{
return b > 0 ? gcd(b,a % b) : a;
}
long long lcm(long long a,long long b){
return a / gcd(a, b) * b;
}
int subarrayLCM(vector<int>& nums, int k) {
int n = nums.size();
long long ans = 0;
for(int i = 0;i < n;i++){
long long tmp = 1;
for(int j = i;j < n;j++){
tmp = lcm(tmp, nums[j]);
if(k % tmp) break;
if(tmp == k) ans++;
}
}
return ans;
}
};
3 逐层排序二叉树所需的最少操作数目
逐层排序二叉树所需的最少操作数目
Solution
/**
* 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:
int minimumOperations(TreeNode* root) {
//层次遍历
int ans = 0;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int len = q.size();
//tmp存该层数据
vector<int> tmp(len);
//开始存数据
for(int i = 0;i < len;i++){
auto x = q.front();
tmp[i] = x->val;
q.pop();
if(x->left){
q.push(x->left);
}
if(x->right){
q.push(x->right);
}
}
//置换环
pair<int, int> arrpos[len];//一维记录数值,一维记录位置
for(int i = 0;i < len;i++){
arrpos[i].first = tmp[i];
arrpos[i].second = i;
}
//跑次数
sort(arrpos,arrpos + len);
vector<int> vis(len,0);
for(int i = 0;i < len;i++){
int cycelsize = 0;
//自环或者访问过
if(vis[i] || arrpos[i].second == i) continue;
int j = i;
while(!vis[j]){
vis[j] = 1;
j = arrpos[j].second;
cycelsize += 1;
}
if(cycelsize > 0){
ans += (cycelsize - 1);
}
}
}
return ans;
}
};
4 不重叠回文子字符串的最大数目
不重叠回文子字符串的最大数目
Solution
class Solution {
public:
int maxPalindromes(string s, int k) {
int n = s.size(), f[n+1];
memset(f, 0, sizeof(f));
for(int i = 0;i < 2 * n - 1;i++){
int l = i / 2, r = l + i % 2;
f[l + 1] = max(f[l + 1], f[l]);
for(; l >= 0 && r < n && s[l] == s[r]; --l, ++r){
if(r + 1 - l >= k){
f[r + 1] = max(f[r + 1], f[l] + 1);
break;
}
}
}
return f[n];
}
};