【LeetCode 0-Start】[数组]二维数组及滚动数组
文章目录
前言
二维数组及滚动数组
题目序号: 118、119、661、598、419
一、[简单]118. 杨辉三角
题目来源
算法思想:数组;
java代码
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new LinkedList<List<Integer>>();
if (numRows == 0) {
return res;
}//如果是0,直接返回,不能返回null
List<Integer> row1 = new LinkedList<Integer>();//第一行
row1.add(1);
//2行以上
res.add(row1);
for (int i = 2; i <= numRows; i++) {
//控制行
List<Integer> temp = new LinkedList<Integer>();//生成的新的行
temp.add(1);
for (int j = 1; j < i-1; j++) {
temp.add(row1.get(j)+row1.get(j-1));//利用前一行来生成当前的行
}
temp.add(1);
res.add(temp);//加入res
row1 = temp;//更新上一行
}
return res;
}
}
二、[简单]119. 杨辉三角 II
题目来源
算法思想:数组;
PS:可以将34行的结果全部保存下来,然后直接将其输出,,,,
java代码
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> row1 = new LinkedList<Integer>();
row1.add(1);//第0行
for (int i = 1; i <= rowIndex; i++) {
//控制行
List<Integer> temp = new LinkedList<Integer>();
temp.add(1);
for (int j = 1; j < i; j++) {
//从2行,开始进行计算
temp.add(row1.get(j)+row1.get(j-1));
}
temp.add(1);
row1 = temp;
}
return row1;
}
}
三、[简单]661. 图片平滑器
题目来源
算法思想:数组;
思路:
- 对于矩阵中的每一个单元格,找所有 9 个包括它自身在内的紧邻的格子;
- 将所有邻居求和sum,同时记录邻居的数目 count;
- 最终的答案就是和sum除以邻居数目count。
java代码
class Solution {
public int[][] imageSmoother(int[][] M) {
int[][] res = new int[M.length][M[0].length];
//遍历每一个结点
for (int i = 0; i < M.length; i++) {
for (int j = 0; j < M[i].length; j++) {
res[i][j] = around(M, i, j);//计算每一个结点平滑后的值
}
}
return res;
}
private int around(int[][] m, int row, int col) {
int sum = 0;//邻居以及自身的和;
int count = 0;//邻居以及自身的数量总和
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int newRow = row + i;
int newCol = col + j;
if (newCol < 0 || newRow < 0 || newCol > m[0].length-1 || newRow > m.length-1) {
//控制边界
continue;
}else {
//符合边界,求和,计算个数
sum += m[newRow][newCol];
count++;
}
}
}
int res = sum / count;//计算平滑值
return res;
}
}
四、[简单]598. 范围求和 II
题目来源
算法思想:数组;
思路:
- 每次操作都是左上角区域从(0, 0)到(a, b)的矩形,必定重叠
- 所以找最小的a乘最小的b就行
java代码
class Solution {
public int maxCount(int m, int n, int[][] ops) {
if (ops.length == 0) {
//如果数组为空
return m * n;
}
int minA = Integer.MAX_VALUE;//a最小值
int minB = Integer.MAX_VALUE;//b最小值
for (int i = 0; i < ops.length; i++) {
//遍历
int[] tmp = ops[i];
int a = tmp[0];
int b = tmp[1];
if (a < minA) {
//a最小值
minA = a;
}
if (b < minB) {
//b最小值
minB = b;
}
}
return minA * minB;//返回a*b
}
}
五、[中等]419. 甲板上的战舰
题目来源
算法思想:数组
思路:
- 通过战舰的头来判断个数,
- 当一个点上面或者左面试X说明它战舰中间部分,跳过即可!
class Solution {
public int countBattleships(char[][] board) {
int rowLen = board.length;//行长
int colLen = board[0].length;//列长
int count = 0;//记录数量
//遍历board
for (int i = 0; i < rowLen; i++) {
for (int j = 0; j < colLen; j++) {
//如果board[i][j]的上面一个位置或者左边一个位置是“X”,说明是船身,跳过
if (board[i][j] == 'X' &&
(i-1 > -1 && board[i-1][j] == 'X') ||
(j-1 > -1 && board[i][j-1] == 'X')) {
continue;//跳过
}
if (board[i][j] == 'X') {
//除以上情况,说明是船头,要记录下来
count++;//计数++;
}
}
}
return count;//返回船数量
}
}