2022-05-11 矩阵 - Java题解
1351. 统计有序矩阵中的负数
给你一个 m * n 的矩阵 grid,矩阵中的元素无论是按行还是按列,都以非递增顺序排列。 请你统计并返回 grid 中 负数 的数目。
class Solution {
public int countNegatives(int[][] grid) {
int cnt = 0;
for(int i = 0; i < grid.length; i++){
for(int j = 0; j < grid[0].length; j++){
if(grid[i][j] < 0){
cnt += (grid[0].length - j); // 非递增序
break;
}
}
}
return cnt;
}
}
思路: 遍历矩阵统计负数个数,由于数字以非递增序排列,所以遍历每一行时,发现负数后可用下标计算直接算出剩余负数的个数。
给你一个 m x n 的整数网格 accounts ,其中 accounts[i][j] 是第 i 位客户在第 j 家银行托管的资产数量。返回最富有客户所拥有的 资产总量 。
客户的 资产总量 就是他们在各家银行托管的资产数量之和。最富有客户就是 资产总量 最大的客户。
class Solution {
public int maximumWealth(int[][] accounts) {
int max = 0;
for(int n = 0; n < accounts.length; n++){
int tempMax = 0;
for(int m = 0; m < accounts[0].length; m++){
tempMax += accounts[n][m];
}
max = (tempMax > max ? tempMax : max);
}
return max;
}
}
思路: 记录矩阵每一行之和,然后逐行比较最大值。
给定一个 n x n 的二进制矩阵 image ,先 水平 翻转图像,然后 反转 图像并返回 结果 。
水平翻转图片就是将图片的每一行都进行翻转,即逆序。
例如,水平翻转 [1,1,0] 的结果是 [0,1,1]。
反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。
例如,反转 [0,1,1] 的结果是 [1,0,0]。
class Solution {
public int[][] flipAndInvertImage(int[][] image) {
for(int n = 0; n < image.length; n++){
for(int i = 0, j = image[n].length - 1; i < j ; i++,j--){
swap(image[n], i, j);
}
}
for(int i = 0; i < image.length; i++){
for(int j = 0; j < image[0].length; j++){
image[i][j] ^= 1;
}
}
return image;
}
public void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
思路: 考察数组逆序,可用双指针从首尾同时进行
可用^=1 来进行01的数字反转
阵对角线 是一条从矩阵最上面行或者最左侧列中的某个元素开始的对角线,沿右下方向一直到矩阵末尾的元素。例如,矩阵 mat 有 6 行 3 列,从 mat[2][0] 开始的 矩阵对角线 将会经过 mat[2][0]、mat[3][1] 和 mat[4][2] 。
给你一个 m * n 的整数矩阵 mat ,请你将同一条 矩阵对角线 上的元素按升序排序后,返回排好序的矩阵。
class Solution {
public int[][] diagonalSort(int[][] mat) {
for(int m = 0, n = 0; n < mat[0].length; n++){
sortDiagonal(mat, m, n);
}
for(int m = 0, n = 0; m < mat.length; m++){
sortDiagonal(mat, m, n);
}
return mat;
}
public void sortDiagonal(int[][] mat, int row, int column){
List<Integer> tempList = new ArrayList<Integer>();
int m = row, n = column;
while(row < mat.length && column < mat[0].length){
tempList.add(mat[row++][column++]);
}
Collections.sort(tempList);
for(int i = 0; i < tempList.size(); i++){
mat[m++][n++] = tempList.get(i);
}
}
}
思路: 将矩阵每一对角线抽取出来,并重新排序,放回原矩阵