第一题
直接依题意即可
class Solution {
public:
vector<double> convertTemperature(double celsius) {
vector<double> a;
a.push_back(celsius + 273.15);
a.push_back(celsius * 1.80 + 32.00);
return a;
}
};
第二题
以i为起点遍历,再在i遍历的基础上找最小公倍数为 K 的子数组,如遇到则计数统计,返回最后统计值即可
class Solution {
public:
int subarrayLCM(vector<int>& nums, int k) {
int n = nums.size();
int ans = 0;
for (int i = 0; i < n; i++) {
int g = nums[i];
for (int j = i; j < n; j++) {
g = g*nums[j]/__gcd(g,nums[j]);
// cout << g << " " << i << endl;
if (g == k) ans++;
else if (g > k) break;
}
}
// int a = 3 , b = 6;
// cout << a*b/__gcd(a,b);
return ans;
}
};
第三题
先层序遍历并返回每一层的值存入数组中,再依次求数组中最少操作的次数,具体找最少操作次数可以通过建立每个元素与其应放位置的映射关系寻找
/**
* 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 getDepth(TreeNode* root)
{
if (NULL == root)
{
return 0;
}
int leftDepth = getDepth(root->left);
int rightDepth = getDepth(root->right);
int treeDepth = leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
return treeDepth;
}
vector<vector<int> > levelOrder(TreeNode* root)
{
vector<vector<int>> vec;
if(root==nullptr) return vec;
queue<TreeNode*> que;
que.push(root);
while(!que.empty())
{
int n=que.size();
vector<int>lev;
TreeNode* node;
for(int i=0;i<n;i++)
{
node=que.front();
que.pop();
lev.push_back(node->val);
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
vec.push_back(lev);
}
return vec;
}
int getMinSwaps(vector<int> &nums)
{
//排序
vector<int> nums1(nums);
sort(nums1.begin(),nums1.end());
unordered_map<int,int> m;
int len = nums.size();
for (int i = 0; i < len; i++){
m[nums1[i]] = i;//建立每个元素与其应放位置的映射关系
}
int loops = 0;//循环节个数
vector<bool> flag(len,false);
//找出循环节的个数
for (int i = 0; i < len; i++){
if (!flag[i]){//已经访问过的位置不再访问
int j = i;
while (!flag[j]){
flag[j] = true;
j = m[nums[j]];//原序列中j位置的元素在有序序列中的位置
}
loops++;
}
}
return len - loops;
}
int minimumOperations(TreeNode* root) {
int deep = getDepth(root);
vector<vector<int> > w = levelOrder(root);
int ans = 0;
for(int i = 0; i < deep; i ++)
{
for(auto x : w[i])cout << x << " ";
// cout << "----" << getMinSwaps(w[i]);
// cout << endl;
ans += getMinSwaps(w[i]);
// cout << i << endl;
}
return ans;
}
};