day7 leetcode(54.59,61)

在这里插入图片描述

螺旋矩阵

在这里插入图片描述

class Solution
{
public:
vector spiralOrder(vector<vector>& matrix)
{
if(matrix.empty()) return {};
vector ans;
int top=0;
int bottom=matrix.size()-1;
int left=0;
int right=matrix[0].size()-1;
while(true){
for(int i=left;i<=right;i++){
ans.push_back(matrix[top][i]) ;
}
top++;
if(top>bottom)break;
for(int i=top;i<=bottom;i++){
ans.push_back(matrix[i][right]);
}
right–;
if(right<left)
break;
for(int i=right;i>=left;i–)
{
ans.push_back(matrix[bottom][i]);
}
bottom–;
if(bottom<top)
break;
for(int i=bottom;i>=top;i–)
{
ans.push_back(matrix[i][left]);
}
left++;
if(left>right)
break;
}
return ans;
}
};
本题我做的时候并没有想到什么算法,只想到了要有四个边界,上下左右。每一次随着边界的变化,一圈一圈的构建新的矩阵。

螺旋矩阵2

在这里插入图片描述
class Solution {
public:
vector<vector> generateMatrix(int n) {
vector<vector> res(n,vector(n));//写法很重要
int top=0;
int bottom=n-1;
int right =n-1;
int left=0;
int w=1;
while(true){
for(int i=left;i<=right;i++)
{
res[top][i]=w;
w++;
}
top++;
if(top>bottom)
break;
for(int i=top;i<=bottom;i++)
{
res[i][right]=w;
w++;
}
right–;
if(right<left)
break;
for(int i=right;i>=left;i–)
{
res[bottom][i]=w;
w++;
}
bottom–;
if(bottom<top)
break;
for(int i=bottom;i>=top;i–)
{
res[i][left]=w;
w++;
}
left++;
if(left>right)
break;
}
return res;

}

};
感觉与第一题相差无几,思路也大致 一样。

旋转矩阵

在这里插入图片描述
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head||!head->next||k0)
return head;
int count=1;
ListNode * p=head;//用来遍历整个链表找出尾指针
ListNode * tail=head;
ListNode * cur_head=head;
while(p->next)
{
p=p->next;
count++;
}
k=k%count;
if(k
0)
return head;
for(int i=1;count-k-i>0;i++)
{
tail=tail->next;
}
for(int i=1;count-k-i+1>0;i++)
{
cur_head=cur_head->next;
}
tail->next=nullptr;
p->next=head;
return cur_head;

}

};
本题的要求是旋转链表,所以找好头尾指针很重要。通过原来链表,和新的链表。这两个链表的两队前后指针,来完成拼接。这道题我认为,如果先行对链表进行遍历找出链表长度,再对k进行取模运算会简化一些。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值