Skip to content

Commit 212f044

Browse files
author
kwu130
committed
feat(src): add 59-generateMatrix, 61-rotateRight
1 parent 8229392 commit 212f044

2 files changed

Lines changed: 119 additions & 0 deletions

File tree

‎src/59-generateMatrix.cpp‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
//
2+
// Created by 1412 on 2025/11/5.
3+
//
4+
5+
#include <bits/stdc++.h>
6+
7+
using namespace std;
8+
9+
class Solution {
10+
public:
11+
vector<vector<int>> generateMatrix(int n) {
12+
vector<vector<int>> res(n, vector<int>(n, 0));
13+
int k = 1;
14+
int i = 0, j = 0;
15+
while (k <= n * n) {
16+
while (j < n && res[i][j] == 0) {
17+
res[i][j] = k++;
18+
j++;
19+
}
20+
j--;
21+
i++;
22+
while (i < n && res[i][j] == 0) {
23+
res[i][j] = k++;
24+
i++;
25+
}
26+
i--;
27+
j--;
28+
while (j >= 0 && res[i][j] == 0) {
29+
res[i][j] = k++;
30+
j--;
31+
}
32+
j++;
33+
i--;
34+
while (i >= 0 && res[i][j] == 0) {
35+
res[i][j] = k++;
36+
i--;
37+
}
38+
i++;
39+
j++;
40+
}
41+
return res;
42+
}
43+
};
44+
45+
void test() {
46+
Solution s;
47+
vector<vector<int>> expected = {
48+
{1, 2, 3},
49+
{8, 9, 4},
50+
{7, 6, 5}
51+
};
52+
vector<vector<int>> res = s.generateMatrix(3);
53+
assert(res == expected);
54+
55+
expected = {{1}};
56+
res = s.generateMatrix(1);
57+
assert(res == expected);
58+
}
59+
60+
int main() {
61+
test();
62+
return 0;
63+
}

‎src/61-rotateRight.cpp‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
//
2+
// Created by 1412 on 2025/11/5.
3+
//
4+
5+
#include <bits/stdc++.h>
6+
#include "../include/common.h"
7+
8+
using namespace std;
9+
using listHelper::ListNode;
10+
11+
class Solution {
12+
public:
13+
ListNode* rotateRight(ListNode* head, int k) {
14+
if (head == nullptr || head->next == nullptr) return head;
15+
int len = 0;
16+
ListNode *cur = head, *pre = nullptr, *tail = nullptr;
17+
while (cur) {
18+
len++;
19+
tail = cur;
20+
cur = cur->next;
21+
}
22+
k %= len;
23+
if (k == 0) return head;
24+
int i = len - k;
25+
cur = head;
26+
while (i--) {
27+
pre = cur;
28+
cur = cur->next;
29+
}
30+
pre->next = nullptr;
31+
tail->next = head;
32+
return cur;
33+
}
34+
};
35+
36+
void test() {
37+
Solution s;
38+
ListNode* head = listHelper::build({1, 2, 3, 4, 5});
39+
ListNode* expected = listHelper::build({4, 5, 1, 2, 3});
40+
ListNode* res = s.rotateRight(head, 2);
41+
assert(listHelper::equal(res, expected));
42+
listHelper::free(head);
43+
listHelper::free(expected);
44+
45+
head = listHelper::build({0, 1, 2});
46+
expected = listHelper::build({2, 0, 1});
47+
res = s.rotateRight(head, 4);
48+
assert(listHelper::equal(res, expected));
49+
listHelper::free(head);
50+
listHelper::free(expected);
51+
}
52+
53+
int main() {
54+
test();
55+
return 0;
56+
}

0 commit comments

Comments
 (0)