[LeetCode] 双周赛33
5479. 千位分隔数
难度:Easy
题目描述:
解题思路:
将n转为字符串后挨个插入即可,注意insert后下标i会出现变化
class Solution {
public:
string thousandSeparator(int n) {
if(n == 0){
return "0";
}
string source = to_string(n);
int len = source.size();
int i = len % 3;
if(i == 0){
i = i+3;
}
for(i; i < len; i+=3){
source.insert(i, ".");
i++;
}
return source;
}
};
5480. 可以到达所有点的最少点数目
难度:Medium
题目描述:
解题思路:
注意此题只需要求出所有入度为0的点就可以。
一种方法是直接遍历得到入度为0的点;
另一种是用两个set分别存入点和出点,遍历起点,如果在终点点的集合中没有,则将其加入结果
class Solution {
public:
vector<int> findSmallestSetOfVertices(int n, vector<vector<int>>& edges) {
vector<int> ans;
unordered_set<int> from,to;
for(auto e:edges){
from.insert(e[0]);
to.insert(e[1]);
}
for(auto i:from){
if(!to.count(i)) ans.push_back(i);
}
return ans;
}
};
5481. 得到目标数组的最少函数调用次数
难度:Medium
题目描述:
解题思路:
提供的函数由两个功能:
- 将某一个数+1
- 将所有的数乘以2
- 先遍历所有的数组元素一遍,有一个奇数,就需要调用一次
- 对所有的数都除以2,调用一次
- 判断当前数组中0的个数,已满直接返回
class Solution {
public:
int minOperations(vector<int>& nums) {
int ans = 0;
while(1){
// 统计有多少位奇数
for(auto& x : nums){
if(x & 1){ // 有奇数就要调用一次加一
ans += 1;
}
x >>= 1; // 除以2
}
int zero = 0; // 统计当前数组中0的个数
for(auto x : nums){
if(x == 0){
zero++;
}
}
if(zero == nums.size()){
break;
}
ans+=1; // 进行了一次全部除以2
}
return ans;
}
};
5482. 二维网格图中探测环(DFS)
难度:Hard
题目描述:
解题思路:
典型的DFS搜索的问题。
对于周围的元素进行搜索,在搜索的过程中会形成一颗树,当访问到非父节点的祖先节点时,形成了环。
需要一个visited数组对已经访问过得元素进行记录。用px,py记录父节点。
- 递归终止条件:访问到Visited中已经访问过的元素
- 递归方程:当周围的坐标不越界,下一个要访问的不是px,py并且字符相同时,dfs当前节点
class Solution {
public:
int dirx[4] = {1, -1, 0, 0};
int diry[4] = {0, 0, 1, -1};
int row, col;
bool containsCycle(vector<vector<char>>& grid) {
row = grid.size();
col = grid[0].size();
vector<vector<int>> visited(row, vector<int>(col, 0));
// 调用dfs寻找当前起点寻找是否存在环
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(!visited[i][j]){
bool flag = dfs(grid, visited, i, j, -1, -1);
if(flag){
return true;
}
}
}
}
return false;
}
bool dfs(vector<vector<char>>& grid, vector<vector<int>>& visited, int x, int y, int px, int py){
visited[x][y] = 1;
for(int i = 0; i < 4; i++){
int nx = x + dirx[i];
int ny = y + diry[i];
if(nx<0 || nx>=row || ny<0 || ny>=col){ // 越界情况
continue;
}
if(nx == px && ny == py){ // 防止重复访问上一个节点
continue;
}
if(grid[x][y] == grid[nx][ny]){
if(visited[nx][ny]){ // 如果下一个点已经访问过,说明出现了环
return true;
}
bool flag = dfs( grid, visited, nx, ny, x, y); // 如果没有访问过,则递归访问
if(flag){
return true;
}
}
}
return false;
}
};