classSolution{int[] dx ={0,1,0,-1};int[] dy ={1,0,-1,0};publicintcountSubIslands(int[][] grid1,int[][] grid2){// 获取行列的行列数int m = grid1.length;int n = grid1[0].length;// 初始化访问与否的二维数组状态为未访问boolean[][] visit =newboolean[m][n];for(int i =0; i < m; i ++){for(int j =0; j < n; j ++){
visit[i][j]=false;}}// dfs遍历,如果当前“岛屿”未访问 且 当前位置为“岛屿”,则res++int res =0;for(int i =0; i < m; i ++){for(int j =0; j < n; j ++){if(!visit[i][j]&& grid2[i][j]==1){
res +=dfs(i, j, visit, grid1, grid2);}}}return res;}// dfs遍历publicintdfs(int x,int y,boolean[][] visit,int[][] g1,int[][] g2){
visit[x][y]=true;int res =1;if(g1[x][y]==0){
res =0;}int m = g1.length;int n = g1[0].length;for(int i =0; i <4; i ++){int tx = x + dx[i];int ty = y + dy[i];if(tx <0|| tx >= m || ty <0|| ty >= n){continue;}if(visit[tx][ty]){continue;}if(g2[tx][ty]==0){continue;}int cur =dfs(tx, ty, visit, g1, g2);if(cur ==0){
res =0;}}return res;}}
查询差绝对值的最小值
classSolution{publicint[]minDifference(int[] nums,int[][] queries){//每个下标为终点时所有数字出现次数int[][] sign =newint[nums.length][101];//中间数组int[] arr =newint[101];for(int i =0; i < nums.length ; i++){
arr[nums[i]]++;
sign[i]= arr.clone();}int n = queries.length;int[] res =newint[n];//初始化答案数组为一个极大值
Arrays.fill(res ,105);for(int i =0; i < n ; i++){int[] copy = queries[i];//左右区间int l = copy[0], r = copy[1];//l和r间所有数字出现次数
arr =newint[101];//在每个数字有出现次数时之前有出现次数的数字int pre =0;//前缀和的差值不会包括l为下标的数字,需加入
arr[nums[l]]++;for(int j =0; j <101; j++){
arr[j]+= sign[r][j]- sign[l][j];if(arr[j]>0){if(pre ==0){//之前无数字出现,pre置为当前数
pre = j;}else{//之前有数字出现,计算差绝对值(从小到大遍历,结果一定大于0),与res[i]比较
res[i]= Math.min(j-pre , res[i]);
pre = j;}}}//可能出现只有一种数字出现的情况,此时置为-1
res[i]= res[i]==105?-1: res[i];}return res;}}