LeetCode 专栏收录该内容
11 篇文章 0 订阅

# 2021.11.21 559.N叉树的最大深度

## 思路

①深度遍历

②广度优先遍历：每次出队要把队列所有的元素拿出来。

## 代码

/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;

Node() {}

Node(int _val) {
val = _val;
}

Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/

class Solution {
public:
int max_depth = 0;
int maxDepth(Node* root) {
dfs(root,0);
return max_depth;
}
void dfs(Node* root,int height){
if(root == NULL) return;
height += 1;
max_depth = max(max_depth,height);
vector<Node*> _children = root->children;
for(int i = 0; i < _children.size(); i++) {
dfs(_children[i],height);
}
}
};

# 2021.11.22 384.打乱数组

## 思路

class Solution {
public:
Solution(vector<int>& nums) {
this->nums = nums;
this->original.resize(nums.size());
copy(nums.begin(), nums.end(), original.begin());
}

vector<int> reset() {
copy(original.begin(), original.end(), nums.begin());
return nums;
}
vector<int> shuffle() {
vector<int> shuffled = vector<int>(nums.size());
list<int> lst(nums.begin(), nums.end());

for (int i = 0; i < nums.size(); ++i) {
int j = rand()%(lst.size());
auto it = lst.begin();
shuffled[i] = *it;
lst.erase(it);
}
copy(shuffled.begin(), shuffled.end(), nums.begin());
return nums;
}
private:
vector<int> nums;
vector<int> original;
};

class Solution {
public:
Solution(vector<int>& nums) {
this->nums = nums;
this->original.resize(nums.size());
copy(nums.begin(), nums.end(), original.begin());
}

vector<int> reset() {
copy(original.begin(), original.end(), nums.begin());
return nums;
}

vector<int> shuffle() {
for (int i = 0; i < nums.size(); ++i) {
int j = i + rand() % (nums.size() - i);
swap(nums[i], nums[j]);
}
return nums;
}
private:
vector<int> nums;
vector<int> original;
};

# 2021.11.23 859.亲密字符串

## 思路

①首先判断两个字符串是否相等，如果相等的话再判断字符串是否有某个字符出现的次数超过1。

②如果两个字符串不想等的话，用下标first和second记录字符串对应位置不相等的下标，遍历一遍字符串，只有当first!=-1&&second!=-1时，而且对应位置的字符能够交换才返回true，其余都返回false。

class Solution {
public:
bool buddyStrings(string s, string goal) {
if (s.size() != goal.size()) {
return false;
}

if (s == goal) {
vector<int> count(26);
for (int i = 0; i < s.size(); i++) {
count[s[i] - 'a']++;
if (count[s[i] - 'a'] > 1) {
return true;
}
}
return false;
} else {
int first = -1, second = -1;
for (int i = 0; i < s.size(); i++) {
if (s[i] != goal[i]) {
if (first == -1)
first = i;
else if (second == -1)
second = i;
else
return false;
}
}

return (second != -1 && s[first] == goal[second] && s[second] == goal[first]);
}
}
};

# 2021.11.25 458.可怜的小猪

• 1
点赞
• 0
评论
• 0
收藏
• 打赏
• 扫一扫，分享海报

03-31 6420
04-17 6107
04-01 5474
04-06 5621
07-08 3187
03-10 4389

dream or nightmare

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。