螺旋矩阵
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(k0)
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进行取模运算会简化一些。