按题意写题,秒了
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)
链表基本操作
/**
* 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)
学习了代码随想录,发现使用的是直接使用原来的链表来进行移除节点操作。虚拟头结点的方法似乎更便捷。