59螺旋矩阵203.移除链表元素

59.螺旋矩阵

题目链接 螺旋矩阵

题目描述

给你一个正整数 n ,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix
image
示例 1:
输入:n = 3
输出:[[1,2,3],[8,9,4],[7,6,5]]

思路

  • 坚持每条边左闭右开的原则(即每条边的终止节点不包含);
  • 边数为奇数时,矩阵最中间会空出一个位置;
  • 每次循环后,向内圈缩,右边界的终止位置也会向内缩小;
  • 每次循环后,初始位置会向内圈移动,即startx++,starty++;

代码

点击查看代码
class Solution {
    public int[][] generateMatrix(int n) {
       int startx=0;
        int starty=0;
        int offset = 1;//控制遍历的边的长度,每次循环右边界收缩一位
        int cnt =1;
        int arr[][] = new int[n][n];
        //圈数
        int loop = n/2;
        while(loop-->0){
            //左闭右开
            int i=startx;
            int j=starty;
			//填充上行从左到右
            for(;j<n-offset;j++){
                arr[i][j] = cnt++;
            }
			//填充右行从上到下
            for( ;i<n-offset;i++){
                arr[i][j] = cnt++;
            }
			//填充下行从右到左
            for(;j>starty;j--){
                arr[i][j] = cnt++;
            }
			//填充左行从下到上
            for(;i>startx;i--){
                arr[i][j] = cnt++;
            }
            startx++;
            starty++;
            offset++;
        }
		//若为边数为奇数则单独给矩阵最中间赋值
        if(n%2!=0){
            arr[startx][starty] =cnt;
        }
        return arr;
    }
}

203.移除链表元素

题目链接 移除链表元素

题目描述

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

代码

1.不加虚拟结点

点击查看代码
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        //头结点为空,提前返回
		if(head==null){
            return head;
        }
        //判断头结点是否需要删除
        while(head!=null&& head.val==val){
            head = head.next;
        }
        //非头结点
        ListNode cur = head;
        while(cur!=null&& cur.next!=null){
            if(cur.next.val==val){
                cur.next = cur.next.next;
            }else {
                cur = cur.next;
            }
        }
        return head;
    }
}

2.添加虚拟结点

点击查看代码
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if(head==null){
            return head;
        }
         ListNode dummy = new ListNode();//定义虚拟结点
        dummy.next = head;
        ListNode cur = dummy;
        while(cur!=null&& cur.next!=null){
            if(cur.next.val==val){
                cur.next = cur.next.next;
            }else{
                cur = cur.next;
            }
        }
        return dummy.next;
    }
}
posted @ 2023-08-12 21:08  像峰一样  阅读(13)  评论(0)    收藏  举报