LeetCode每日一题——Day16

59. 螺旋矩阵 II

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix 。

示例 1:

LeetCode每日一题——Day16_第1张图片

输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

示例 2:

输入:n = 1
输出:[[1]]

思路分析:

        采用模拟法,设立四个边界left,right,top,bottom,遵循从左到右,从上到下,从右到左, 从下到上的规律进行模拟。以示例一为例:

        从左到右:从左往右依次填充,填充完毕后上边界下移。

for (int i = left;i <= right;i++)ans[top][i] = num++;
     top++;

        从上到下:从左到右填充完毕后,从上到下开始填充,填充完毕后右边界左移。

for (int i = top;i <= bottom;i++)ans[i][right] = num++;
     right--;

        从右到左:从上到下填充完毕后,从右往左继续填充,填充完毕下边界上移。

for (int i = right;i >= left;i--)ans[bottom][i] = num++;
     bottom--;

        从下到上:同理

for (int i =bottom;i >= top;i--)ans[i][left] = num++;
     left++;

代码实现:

class Solution {
    public int[][] generateMatrix(int n) {
        int left = 0,right = n -1,top = 0,bottom = n -1;
        int [][] ans = new int [n][n];
        int num = 1;
        while(num <= n * n){
            for (int i = left;i <= right;i++)ans[top][i] = num++;
                top++;
            for (int i = top;i <= bottom;i++)ans[i][right] = num++;
                right--;
            for (int i = right;i >= left;i--)ans[bottom][i] = num++;
                bottom--;
            for (int i =bottom;i >= top;i--)ans[i][left] = num++;
                left++;
        }
        return ans;
    }
}

提交结果:

20 / 20 个通过测试用例

状态:通过

执行用时: 0 ms

内存消耗: 39.8 MB

提交时间:38 分钟前


203. 移除链表元素

给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。

示例 1:

LeetCode每日一题——Day16_第2张图片

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

示例 2:

输入:head = [], val = 1
输出:[]

示例 3:

输入:head = [7,7,7,7], val = 7
输出:[]

思路分析:

        链表本身具有递归的性质,我们可以考虑递归的方法实现。

        如果head为空,返回head。head不为空,head.val == val,head被删除,头结点变为head.next。

代码实现:

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null)return head;
            head.next = removeElements(head.next,val);
            return head.val == val?head.next:head;
        }
}

提交结果: 

66 / 66 个通过测试用例

状态:通过

执行用时: 1 ms

内存消耗: 42.1 MB

提交时间:29 分钟前

你可能感兴趣的:(LeetCode每日一题,leetcode,算法,java,链表,数据结构)