> 文章列表 > java数据结构刷题二期

java数据结构刷题二期

java数据结构刷题二期

在 MATLAB 中,有一个非常有用的函数 reshape ,它可以将一个 m x n 矩阵重塑为另一个大小不同(r x c)的新矩阵,但保留其原始数据。

给你一个由二维数组 mat 表示的 m x n 矩阵,以及两个正整数 r 和 c ,分别表示想要的重构的矩阵的行数和列数。

重构后的矩阵需要将原始矩阵的所有元素以相同的 行遍历顺序 填充。

如果具有给定参数的 reshape 操作是可行且合理的,则输出新的重塑矩阵;否则,输出原始矩阵。

示例 1:

输入:mat = [[1,2],[3,4]], r = 1, c = 4
输出:[[1,2,3,4]]
示例 2:

输入:mat = [[1,2],[3,4]], r = 2, c = 4
输出:[[1,2],[3,4]]

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/reshape-the-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {public int[][] matrixReshape(int[][] mat, int r, int c) {//给定参数不合理if(r * c != mat.length * mat[0].length){return mat;}//参数合理int[][] arr = new int[r][c];int n = mat[0].length;//原数组的列数//将二维数组映射到一维数组中//映射行:元素位数 / 数组列数//映射列:元素位数 % 数组列数for (int i = 0; i < r * c; i++) {arr[i / c][i % c] = mat[i / n][i % n];}return arr;}
}作者:frosty-7ichtermanwgr
链接:https://leetcode.cn/problems/reshape-the-matrix/solution/566-zhong-su-ju-zhen-by-frosty-7ichterma-fjcl/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
解法二
class Solution {public int[][] matrixReshape(int[][] mat, int r, int c) {int m = mat.length, n = mat[0].length, x = 0;if(m * n != r * c) return mat;HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();for(int i = 0; i < m; ++i){for(int j = 0; j < n; ++j){hash.put(x++, mat[i][j]);}}int[][] newMat = new int[r][c];for(int i = 0; i < r; ++i){for(int j = 0; j < c; ++j){newMat[i][j] = hash.get(i*c + j);}}作者:azure-ku
链接:https://leetcode.cn/problems/reshape-the-matrix/solution/hashmapshi-xian-by-azure-ku-9tq9/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

题目二

给定一个非负整数 numRows生成「杨辉三角」的前 numRows 行。

在「杨辉三角」中,每个数是它左上方和右上方的数的和。

示例 1:

输入: numRows = 5
输出: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

示例 2:

输入: numRows = 1
输出: [[1]]
class Solution {public static List<List<Integer>> generate(int numRows) {ArrayList<List<Integer>> lists = new ArrayList<>();ArrayList<Integer> integers1 = new ArrayList<>();//定义一个临时存储上一行结果的集合ArrayList<Integer> temp = integers1;for (int i = 1; i <= numRows; i++) {temp = getRow(temp, i);lists.add(temp);}return lists;}//该方法通过上一行的数据计算出本行的数据public static ArrayList<Integer> getRow(List<Integer> list, int n) {ArrayList<Integer> integers = new ArrayList<>();for (int i = 0; i < n; i++) {if (i == 0 || i == n - 1) {integers.add(1);} else {integers.add(list.get(i - 1) + list.get(i));}}return integers;}
}作者:tj-xiong
链接:https://leetcode.cn/problems/pascals-triangle/solution/118yang-hui-san-jiao-by-tj-xiong-0pje/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。