832. 翻转图像
https://leetcode-cn.com/problems/flipping-an-image/
给定一个二进制矩阵 A,我们想先水平翻转图像,然后反转图像并返回果。
水平翻转图片就是将图片的每一行都进行翻转,即逆序。例如,水平翻转 [1, 1, 0] 的结果是 [0, 1, 1]。
反转图片的意思是图片中的 0 全部被 1 替换, 1 全部被 0 替换。例如,反转 [0, 1, 1] 的结果是 [1, 0, 0]。
提示:
1 <= A.length = A[0].length <= 20
0 <= A[i][j] <= 1
根据题目,我们可以得知 水平翻转和反转是怎么玩的。。
首先,创建一个临时的变量,用来保存结果
水平翻转是把索引为0的数和倒数第1个数,索引为1的数,与倒数第2个数…互换位置,而反转是将0换成1,1换成0,所以我们可以直接在水平翻转的同时,直接进行反转
反转让当前这个数直接减去1然后在✖️ - 1 就可以将 0变为1,1变为0
class Solution {
public int[][] flipAndInvertImage(int[][] image) {
int[][] temp = new int[image.length][image[0].length];
for (int i = 0; i < image.length; i++) {
for (int i1 = 0; i1 < image[i].length; i1++) {
temp[i][i1] = (image[i][image[i].length - 1 - i1] - 1) * -1;
}
}
return temp;
}
}
1582. 二进制矩阵中的特殊位置
https://leetcode-cn.com/problems/special-positions-in-a-binary-matrix/
给你一个大小为 rows x cols 的矩阵 mat,其中 mat[i][j] 是 0 或 1,请返回 矩阵 mat 中特殊位置的数目 。
特殊位置 定义:如果 mat[i][j] == 1 并且第 i 行和第 j 列中的所有其他元素均为 0(行和列的下标均 从 0 开始 ),则位置 (i, j) 被称为特殊位置。
这一题我是用到了map结构,用来存储每一行里面只有一个1的行和列,然后再查找下当前列中是否只有一个为1的,是不是当前这个map里面存储的行列,如果当前列有多的1,那么将当前这个key,value删除,剩下的就是符合结果的位置了,只不过这个方法运行时间和占用的内存有点多
class Solution {
public int numSpecial(int[][] mat) {
int res = 0;
Map<Integer,Integer> m = new HashMap<>();
for (int i = 0; i < mat.length; i++) {
for (int i1 = 0; i1 < mat[i].length; i1++) {
if(mat[i][i1] == 1){
if(!m.containsKey(i)){
m.put(i,i1);
}else{
m.remove(i);
break;
}
}
}
}
for (Integer row : m.keySet()) {
for (int i = 0; i < mat.length; i++) {
if(i != row && mat[i][m.get(row)] == 1) {m.put(row,null);break;};
}
if (m.get(row) != null) res++;
}
return res;
}
}
1672. 最富有客户的资产总量
https://leetcode-cn.com/problems/richest-customer-wealth/
给你一个 m x n 的整数网格 accounts ,其中 accounts[i][j] 是第 i 位客户在第 j 家银行托管的资产数量。返回最富有客户所拥有的 资产总量 。
客户的 资产总量 就是他们在各家银行托管的资产数量之和。最富有客户就是 资产总量 最大的客户。
这道题是写了一个for循环的和一个递归的
思路就是,把每一行的数组计算出总和,然后再判断哪一行的总和最大,结果就是最大的那行数组的总和
for循环
class Solution {
public int maximumWealth(int[][] accounts) {
Integer res = 0;
for (int i = 0; i < accounts.length; i++) {
Integer r = 0;
for (int j = 0; j < accounts[i].length; j++) {
r+= accounts[i][j];
}
if(res < r){
res = r;
}
}
return res;
}
}
递归 + for
class Solution {
public int maximumWealth(int[][] accounts) {
Integer res = 0;
for (int i = 0; i < accounts.length; i++) {
int a = getValue(accounts[i],accounts[i].length,0);
if(res < a){
res = a;
}
}
return res;
}
public Integer getValue(int[] nump,int index,int n){
if(index == 0) return 0;
n = nump[index-1];
return n + getValue(nump,index - 1,n);
}
}
递归
class Solution {
public int maximumWealth(int[][] accounts) {
return getNums(accounts,accounts.length,0);
}
public Integer getNums(int[][] nums,int index,int n){
if(index == 0) return n;
int a = getValue(nums[index - 1],nums[index - 1].length,0);
if(a > n) n = a;
return getNums(nums,index - 1,n);
}
public Integer getValue(int[] nump,int index,int n){
if(index == 0) return 0;
n = nump[index-1];
return n + getValue(nump,index - 1,n);
}
}