59. 螺旋矩阵 II
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n, 0));
if (n == 0) return res;
int num = 1;
int left = 0, right = n - 1;
int low = 0, hight = n - 1;
while (left <= right && low <= hight) {
for (int i = left; i <= right; i++) {
res[low][i] = num++;
}
low++;
if (low > hight) break;
for (int i = low;i <=hight; i++ ) {
res[i][right] = num++;
}
right--;
if (right < left) break;
for (int i = right;i >=left;i--) {
res[hight][i] = num++;
}
hight--;
for (int i = hight;i >= low; i--) {
res[i][left] = num++;
}
left++;
}
return res;
}
};
61. 旋转链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head) return NULL;
int n=0;
for(auto p=head;p;p=p->next) n++;
k%=n;
auto first=head,second=head;
while(k--){
first=first->next;
}
while(first->next){
first=first->next;
second=second->next;
}
first->next=head;
head=second->next;
second->next=NULL;
return head;
}
};
54. 螺旋矩阵
class Solution {
private:
static constexpr int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return {};
}
int rows = matrix.size(), columns = matrix[0].size();
vector<vector<bool>> visited(rows, vector<bool>(columns));
int total = rows * columns;
vector<int> order(total);
int row = 0, column = 0;
int directionIndex = 0;
for (int i = 0; i < total; i++) {
order[i] = matrix[row][column];
visited[row][column] = true;
int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
directionIndex = (directionIndex + 1) % 4;
}
row += directions[directionIndex][0];
column += directions[directionIndex][1];
}
return order;
}
};