每周记录24/5/5

59. 螺旋矩阵 II - 力扣(LeetCode)

按题意写题,秒了

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        listn=[[0 for i in range(n+2)] for i in range(n+2)]
        for i in range(0,n+2):
            listn[0][i]=1
            listn[n+1][i]=1
            listn[i][0]=1
            listn[i][n+1]=1
        direct=0
        each=0
        x=1
        y=0
        while True:
            if each==n*n:
                break
            each+=1
            if direct==0:
                if listn[x][y+1]==0:
                    y+=1
                    listn[x][y]=each
                else:
                    direct=1
                    each-=1
            elif direct==1:
                if listn[x+1][y]==0:
                    x+=1
                    listn[x][y]=each
                else:
                    direct=2
                    each-=1 
            elif direct==2:
                if listn[x][y-1]==0:
                    y-=1
                    listn[x][y]=each
                else:
                    direct=3
                    each-=1
            elif direct==3:
                if listn[x-1][y]==0:
                    x-=1
                    listn[x][y]=each
                else:
                    direct=0
                    each-=1
        result=[row[1:n+1] for row in listn[1:n+1]]
        return result

时间复杂度O(n^2),空间复杂度O(n^2)

203. 移除链表元素 - 力扣(LeetCode)

链表基本操作

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        while (head != NULL && head->val == val)
        {
            ListNode* tmp = head;
            head = head->next;
        }
        if (head==NULL)
            return head;
        ListNode* node=head;
        while(node->next != NULL)
        {
            if (node->next->val==val)
                node->next=node->next->next;
            else
                node=node->next;
        }
        return head;
    }
};

时间复杂度O(n),空间复杂度O(1)

学习了代码随想录,发现使用的是直接使用原来的链表来进行移除节点操作。虚拟头结点的方法似乎更便捷。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值