文章目录
- [1556. 千位分隔数](https://leetcode-cn.com/problems/thousand-separator/)(找规律)
- [1557. 可以到达所有点的最少点数目](https://leetcode-cn.com/problems/minimum-number-of-vertices-to-reach-all-nodes/)(找入度为0的点)
- [1558. 得到目标数组的最少函数调用次数](https://leetcode-cn.com/problems/minimum-numbers-of-function-calls-to-make-target-array/)(从二进制角度分析,贪心题)
- [1559. 二维网格图中探测环](https://leetcode-cn.com/problems/detect-cycles-in-2d-grid/)(无向图找环)
- y总视频学习地址
1556. 千位分隔数(找规律)
to_string()
转换为字符串
class Solution {
public:
string thousandSeparator(int n) {
string num = to_string(n); // to_string() 转换为字符串
string res;
for(int i = num.size() - 1, j = 0; i >= 0 ; i-- ,j ++)
{
if(j % 3 == 0 && j) res += '.';
res += num[i];
}
reverse(res.begin(),res.end()); // 翻转字符串
return res;
}
};
1557. 可以到达所有点的最少点数目(找入度为0的点)
class Solution {
public:
vector<int> findSmallestSetOfVertices(int n, vector<vector<int>>& edges) {
// 统计入度为0的点
vector<int> d(n);
for(auto &e : edges)
{
int a = e[0], b = e[1];
d[b] ++;
}
vector<int> res;
for(int i=0;i<n;i++)
if(!d[i])
res.push_back(i);
return res;
}
};
1558. 得到目标数组的最少函数调用次数(从二进制角度分析,贪心题)
class Solution {
public:
int minOperations(vector<int>& nums) {
// 从二进制角度分析,贪心题
int k = 0, o = 0; // k:最大位数, o:0的个数
for(auto x : nums)
{
int bits = 0, ones = 0;
while(x)
{
if(x & 1) ones ++;
bits ++;
x >>= 1;
}
k = max(k,bits), o += ones;
}
return k + o - 1; // 从最大数分析,答案必然是最大位数 + 各个数二进制1的个数
}
};
1559. 二维网格图中探测环(无向图找环)
dfs1
class Solution {
public:
vector<vector<char>> g;
vector<vector<bool>> st;
int n, m;
bool containsCycle(vector<vector<char>>& grid) {
g = grid, n = grid.size(), m = grid[0].size();
st = vector<vector<bool>>(g.size(),vector<bool>(g[0].size()));
for(int i = 0; i < n;i ++)
for(int j = 0;j < m;j ++ )
if(!st[i][j] && dfs(i,j,-1))
return true;
return false;
}
int dx[4] = {-1,1,0,0}, dy[4] = {0,0,-1,1}; // 上下左右
bool dfs(int x,int y,int p){ // p :来时的边,不能往回走
st[x][y] = true;
for(int i=0;i<4;i++)
if(i != p){
int a = x + dx[i], b = y + dy[i];
if(a >= 0 && a < n && b >= 0 && b < m && g[a][b] == g[x][y]){
if(st[a][b]) return true;
if(dfs(a, b, i ^ 1)) return true; // i ^ 1就是反向边,0 ^ 1 = 1,1 ^ 0 = 0
// 2 ^ 1 = 3, 3 ^ 1= 2; 不过要把方向定为上下左右?
}
}
return false;
}
};
dfs2 -------- 这种比较好理解,并且适应leetcode答题模式
const int N = 510;
int n, m;
vector<vector<char>> g;
bool st[N][N];
int dx[4] = {-1,0,1,0}, dy[4] = {0,1,0,-1};
bool dfs(int x,int y,int lastx,int lasty)
{
st[x][y] = true;
for(int i=0;i<4;i++)
{
int a = x + dx[i], b = y + dy[i];
// 非法情况
if(a < 0 || a >= n || b < 0 || b >= m) continue;
if(g[a][b] != g[x][y]) continue;
if(a == lastx && b == lasty) continue;
if(st[a][b]) return true;
if(dfs(a,b,x,y)) return true;
}
return false;
}
class Solution {
public:
bool containsCycle(vector<vector<char>>& grid) {
g = grid;
n = grid.size(), m = grid[0].size();
memset(st,0,sizeof st);
for(int i = 0;i < n ;i ++ )
for(int j = 0; j < m;j ++ )
if(!st[i][j] && dfs(i,j,-1,-1))
return true;
return false;
}
};