Leetcode 498. 对角线遍历

Leetcode 498. 对角线遍历_第1张图片
思路1:跟对角线遍历相似, i+j 为偶数时向上走,i+j 为奇数时向下走
所以偶数对角线从头部加入元素LinkedList.addFirst,奇数对角线从尾部加入元素LinkedList.addLast,注意,只有LinkedList才有头插法和尾插法

class Solution {
     
    public static int[] findDiagonalOrder(int[][] matrix) {
     
        Map<Integer, LinkedList<Integer>> map = new LinkedHashMap<>();
        int row = matrix.length;
        if (row == 0)   return new int[0];
        int col = matrix[0].length;
        for (int i = 0; i < row; i++) {
     
            for (int j = 0; j < col; j++) {
     
                if (!map.containsKey(i+j))
                    map.put(i+j, new LinkedList<>());
                if ((i+j) % 2 ==0)
                    map.get(i+j).addFirst(matrix[i][j]);
                if ((i+j) % 2== 1)
                    map.get(i+j).addLast(matrix[i][j]);
            }
        }
        int[] ans = new int[row*col];
        int index = 0;
        for (Integer key : map.keySet()) {
     
            List<Integer> list = map.get(key);
            for (int i = 0; i < list.size(); i++) {
     
                ans[index++] = list.get(i);
            }
        }
        return ans;
    }

    public static void main(String[] args) {
     
        int[][] p = {
     {
     1,2,3},{
     4,5,6},{
     7,8,9}};
        int[] ans = findDiagonalOrder(p);
        for (int an : ans) {
     
            System.out.print(an + " ");
        }
    }
}

思路2:对角线条数 m+n-1
越界处理(右上)
1.n 这种情况m++即可
2.n>=columnLength 3到6的情形
这种呢m+2,n–即可

越界处理(左下)
1.m 这种情况n++即可
2.m>=rowLength 8到9的情形
这种呢n+2,m–即可

Leetcode 498. 对角线遍历_第2张图片

class Solution {
     
    public static int[] findDiagonalOrder(int[][] matrix) {
     
        if (matrix.length == 0) {
     
            return new int[0];
        }
        int row_length = matrix.length;
        int col_length = matrix[0].length;
        int[] ans = new int[row_length * col_length];
        int count = row_length + col_length - 1;
        int m = 0, n = 0, index = 0;
        for (int i = 0; i < count; i++) {
     
        	// 右上
            if (i % 2 == 0) {
     
                while (m >= 0 && n < col_length) {
     
                    ans[index++] = matrix[m][n];
                    m--;
                    n++;
                }
                if (n < col_length) {
     
                    m++;
                } else {
     
                    m += 2;
                    n--;
                }
                //左下
            } else {
     
                while (n >= 0 && m < row_length) {
     
                    ans[index++] = matrix[m][n];
                    m++;
                    n--;
                }
                if (m < row_length) {
     
                    n++;
                } else {
     
                    m--;
                    n += 2;
                }
            }
        }
        return ans;
    }
}

你可能感兴趣的:(Leetcode,数组)