Data structure brush questions basic version

Yebyebi, I also wish myself a happy holiday duck, and also, study hard

content

1. Yanghui Triangle

2. Reshape the matrix


1. Yanghui Triangle

118. Yang Hui Triangle - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/pascals-triangle/submissions/

Topics and examples:

Problem-solving ideas: (note that there are still lists in the list)

①The idea of ​​conversion (thinking of converting Yang Hui's triangle into a matrix for thinking)

②Utilize the content about the collection

 code show as below:

class Solution {
 public List<List<Integer>> generate(int numRows) {
        List<List<Integer>>tmp=new ArrayList<>();
        int [][]nums=new int[numRows][numRows];
        for(int i=0;i<nums.length;i++){
            List<Integer>list=new ArrayList<>();
            for(int j=0;j<=i;j++){
                if(j==0||i==j){
                    nums[i][j]=1;
                }else{
                    nums[i][j]=nums[i-1][j-1]+nums[i-1][j];
                }list.add(nums[i][j]);
            }
            tmp.add(list);
        }return tmp;
 }
}

2. Reshape the matrix

566. Reshape the Matrix - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/reshape-the-matrix/

Topics and examples:

Problem-solving ideas: (conversion ideas, mutual conversion of one-dimensional arrays and two-dimensional arrays) 

① Convert a two-dimensional array to a one-dimensional array

②Convert the one-dimensional array into the required two-dimensional array

a. About how to turn a two-dimensional array into a one-dimensional array

b. Analysis of this topic as an example

code show as below:

class Solution {
    public int[][] matrixReshape(int[][] mat, int r, int c) {
   //把二维数组看做一维数组后求数组的长度
   int m=mat.length;
   //每个被看做一维数组的对应的长度
   int n=mat[0].length;
   //简单判断,若二维数组切换前后数据的数量发生了改变,那么显然是不能够进行成功切换的
   if(m*n!=r*c){
       return mat;
   }
   //创建一个新数组用来接收r行,c列的数组
   int tmp[][]=new int[r][c];
   //判断二维数组中每个数在变成一维数组后的位置
   int newposition=0;
   for(int i=0;i<r;i++){
       for(int j=0;j<c;j++){
           tmp[i][j]=mat[newposition/n][newposition%n];
           newposition++;
       }
   }return tmp;
}
}

Guess you like

Origin blog.csdn.net/weixin_58850105/article/details/123350945