leetCode打卡
一、乘积小于K的子数组
-
题目:
-
题解(滑动窗口):
class Solution {
public:
int numSubarrayProductLessThanK(vector<int>& nums, int k) {
if(nums.empty()||k==0||k==1) return 0;
int left=0,right=0,base=1,times=0;
while(right<nums.size()){
base*=nums[right];
while(base>=k) base/=nums[left++];
times+=right-left+1;
right++;
}
return times;
}
};
二、长度最小的子数组
-
题目:
-
题解(滑动):
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int sum=0;
for(int i=0;i<nums.size();i++) sum+=nums[i];
if(sum==target) return nums.size();
if(sum<target) return 0;
int base=0,lenMin=INT_MAX;
for(int left=0,right=0;right<nums.size();right++){
base+=nums[right];
while(base>=target) lenMin=min(lenMin,right-left+1),base-=nums[left++];
}
return lenMin==INT_MAX?0:lenMin;
}
};
三、岛屿数量
- 题目:
- 题解:
- 方法一(深度优先搜索dfs):
int numIslands(vector<vector<char>>& grid) {
int m = grid.size(),n = grid[0].size();
if(m<0) return 0;
int num=0;
for(int r=0;r<m;r++){
for(int c=0;c<n;c++){
if(grid[r][c]=='1'){
num++;
dfs(grid,r,c);
}
}
}
return num;
}
void dfs(vector<vector<char>>& grid,int r,int c){
int mr = grid.size(),nc=grid[0].size();
grid[r][c]='0';
if(r-1>=0&&grid[r-1][c]=='1') dfs(grid,r-1,c);
if(r+1<mr&&grid[r+1][c]=='1') dfs(grid,r+1,c);
if(c-1>=0&&grid[r][c-1]=='1') dfs(grid,r,c-1);
if(c+1<nc&&grid[r][c+1]=='1') dfs(grid,r,c+1);
}
- 方法二(广度优先搜索):
int numIslands(vector<vector<char>>&grid){
int mr=grid.size(),nc=grid[0].size();
if(mr<0) return 0;
int numIsland=0;
for(int r=0;r<mr;r++){
for(int c=0;c<nc;c++){
if(grid[r][c]=='1'){
numIsland++;
grid[r][c]='0';
queue<pair<int ,int>>neighbors;
neighbors.push({r,c});
while(!neighbors.empty()){
auto rc=neighbors.front();
neighbors.pop();
int r1=rc.first,c1=rc.second;
if(r1-1>=0&&grid[r1-1][c1]=='1'){
neighbors.push({r1-1,c1});
grid[r1-1][c1]='0';
}
if(r1+1<mr&&grid[r1+1][c1]=='1'){
neighbors.push({r1+1,c1});
grid[r1+1][c1]='0';
}
if(c1-1>=0&&grid[r1][c1-1]=='1'){
neighbors.push({r1,c1-1});
grid[r1][c1-1]='0';
}
if(c1+1<nc&&grid[r1][c1+1]=='1'){
neighbors.push({r1,c1+1});
grid[r1][c1+1]='0';
}
}
}
}
}
return numIsland;
}
四、省份数量
- 题目:
- 题解:
- 方法一(深度优先搜索):
int findCircleNum(vector<vector<int>>& isConnected) {
int n = isConnected.size();
vector<int>city(n,0);
int province=0;
for(int i=0;i<n;i++){
if(!city[i]){
dfs(isConnected,city,i);
province++;
}
}
return province;
}
void dfs(vector<vector<int>>&isConnected,vector<int>&city,const int&i){
for(int j=0;j<isConnected.size();j++){
if(isConnected[i][j]==1&&city[j]==0){
city[j]=1;
dfs(isConnected,city,j);
}
}
}
- 方法二(广度优先搜索):
int findCircleNum(vector<vector<int>>&isConnected){
int n =isConnected.size();
vector<int>city(n,0);
int province=0;
queue<int>que;
for(int i=0;i<n;i++){
if(!city[i]){
que.push(i);
while(!que.empty()){
int Q = que.front();
que.pop();
city[Q]=1;
for(int j=0;j<n;j++){
if(isConnected[Q][j]==1&&city[j]==0){
que.push(j);
}
}
}
province++;
}
}
return province;
}