题目一要求:
具体代码一
用递归实现:典型回溯法,对于任意一个节点,先把左右儿子交换完成,左右儿子完成之后,再针对本次节点交换左右指针,那么本次节点结束,返回上一层
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
isChange(root);
return root;
}
void isChange(TreeNode* root) {
if (root == nullptr) {
return ;
}
isChange(root->left);
isChange(root->right);
if (left&&right) {
swap(root->left, root->right);
}
}
};
(所有代码均已在力扣上运行无误)
经测试,该代码运行情况是(经过多次测试所得最短时间):
具体代码二
迭代实现:
在层次遍历的过程中,可以层为基本单位,也可以尝试以单个点为基准,不好判断就都尝试。以层为基础尝试过后很复杂,所以尝试以点为基准,一定要认真读题,好好理解题目中的翻转,本题中以点为基准的时候恰好就是题目要求。
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if (root == nullptr) {
return root;
}
queue<TreeNode*> help;
help.push(root);
while (!help.empty()) {
TreeNode* temp = help.front();
help.pop();
if (temp->left != nullptr) {
help.push(temp->left);
}
if (temp->right != nullptr) {
help.push(temp->right);
}
swap(temp->left, temp->right);
}
return root;
}
};
(所有代码均已在力扣上运行无误)
经测试,该代码运行情况是(经过多次测试所得最短时间):
时间复杂度:
题目二要求:
整体思路 :贪心
1、总体思想就是贪心,我总是想以最低价格购入。
2、因为我们不能以后出现的价格买入,一先出现的价格卖出,所以我们一旦选择了某一个价格买入后,那么前面的价格就无用了。
3、我们每次都是以最低价格买入,所以一定可以卖出。
4、我就是要挑选最低价格,保证了最低价格后,找最大收益就行。
具体代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int ans = 0;
int mins = 1 << 30;
for (int i = 0; i < n; i++) {
if (mins <= prices[i]) {
ans = max(prices[i] - mins, ans);//当前价格大于最低价格,那么就计算收益就行
}
else {
mins = prices[i];//更新最低价格
}
}
return ans;
}
};
(所有代码均已在力扣上运行无误)
经测试,该代码运行情况是(经过多次测试所得最短时间):
时空复杂度:
遍历了一遍数组,时间复杂度O(N),空间复杂度O(1)