DataWhale task06

螺旋矩阵

class Solution {
    public List spiralOrder(int[][] matrix) {
        List order = new ArrayList();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return order;
        }
        int rows = matrix.length, columns = matrix[0].length;
        int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
        while (left <= right && top <= bottom) {
            for (int column = left; column <= right; column++) {
                order.add(matrix[top][column]);
            }
            for (int row = top + 1; row <= bottom; row++) {
                order.add(matrix[row][right]);
            }
            if (left < right && top < bottom) {
                for (int column = right - 1; column > left; column--) {
                    order.add(matrix[bottom][column]);
                }
                for (int row = bottom; row > top; row--) {
                    order.add(matrix[row][left]);
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return order;
    }
}

螺旋矩阵 II

class Solution {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int i = 0;
        int j = 0;
        int count = 1;

        // 方向值,0 向右;1 向下;2 向左;3 向上
        int direction = 0;
        while (count <= n * n) {
            res[i][j] = count;
            switch (direction) {
                case 0: 
                    if (j == n - 1 || res[i][j + 1] != 0) {
                        direction = 1;
                        i++;
                    }
                    else j++;
                    break;
                case 1:
                    if (i == n - 1 || res[i + 1][j] != 0) {
                        direction = 2;
                        j--;
                    }
                    else  i++;
                    break;
                case 2:
                    if (j == 0 || res[i][j - 1] != 0) {
                        direction = 3;
                        i--;
                    }
                    else j--;
                    break;
                case 3:
                    if (i == 0 || res[i - 1][j] != 0) {
                        direction = 0;
                        j++;
                    }
                    else i--;
                    break;
            }
            count++;
        }
        return res;
    }
}

旋转链表

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null || k ==0){
            return head;
        }
        ListNode headBak = head;

        int len = 0;
        while(head.next!=null){
            head = head.next;
            len++;
        }
        k = k%(++len);

        if(k == 0){
            return headBak;
        }
        head.next = headBak;

        k = len-k;
        len = 0;
        while(len

你可能感兴趣的:(DataWhale task06)