*************
C++
topic: 189. 轮转数组 - 力扣(LeetCode)
*************
Give the topic a inspection.
![]() |
This topic looks like an easy one and just make another vector to store the changed vector.
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
}
};
And then iterate through the entire vector. Before that, I really enjoy using the basic usages in vector. Here are some basic usages of vector in c++.
create and initialise
vector<int> v1; // 空 → []
vector<int> v2(3); // 3个0 → [0,0,0]
vector<int> v3 = {1, 2, 3}; // → [1,2,3]
vector<string> v4(2, "A"); // → ["A","A"]
add some elements
vector<int> v = {1, 2};
v.push_back(3); // → [1,2,3] (尾部插入)
v.emplace_back(4); // → [1,2,3,4] (更高效)
v.insert(v.begin(), 0);// → [0,1,2,3,4] (开头插入)
v.insert(v.begin()+2, 9); // → [0,1,9,2,3,4] (第3位插入)
vector<int> v = {1, 2, 3, 4, 5, 6, 7};
// 在开头插入最后3个元素(5,6,7)
v.insert(v.begin(), v.end() - 3, v.end()); // 输出:5 6 7 1 2 3 4 5 6 7
delete some elements
vector<int> v = {10,20,30,40};
v.pop_back(); // → [10,20,30](删除尾部)
v.erase(v.begin()+1); // → [10,30] (删除第2个元素)
v.clear(); // → [] (清空)
visit the element
vector<int> v = {5,6,7};
int a = v[0]; // a=5(不检查越界)
int b = v.at(1); // b=6(越界会抛异常)
int c = v.front(); // c=5(首元素)
int d = v.back(); // d=7(尾元素)
change the size of the vector
vector<int> v = {1,2};
v.resize(4); // → [1,2,0,0](填充0到4个元素)
v.resize(3); // → [1,2,0] (截断到3个)
v.reserve(10); // 容量变为10,但元素不变
This is almost the 5 time I learn how to do the basic usages of the vector.
class Solution {
public:
void rotate(vector<int>& nums, int k) {
nums.insert(nums.begin(), nums.end() - k, nums.end());
nums.erase(nums.end() - k, nums.end());
}
};
![]() |
add something.
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
if (k > n)
{
k = k % n;
}
nums.insert(nums.begin(), nums.end() - k, nums.end());
nums.erase(nums.end() - k, nums.end());
}
};
![]() |
traditional manipulate: debug.
步骤 | 当前执行代码行 | 变量状态变化 | 条件判断 | 循环迭代 | 输出内容 | 操作注释 |
---|---|---|---|---|---|---|
1 | void rotate(...) | nums = [1,2,3], k = 1 | - | - | - | 进入函数 |
2 | int n = nums.size() | n = 3 (原数组长度) | - | - | - | 获取数组长度 |
3 | if (k > n) | k (1) ≤ n (3) → false | 不执行if块 | - | - | 检查k是否需要取模 |
4 | nums.insert(...) | nums = [1,2,3] → [3,1,2,3] | - | - | - | 插入后k个元素到开头 |
5 | nums.erase(...) | nums = [3,1,2,3] → [3,1,2] | - | - | - | 删除最后k个元素 |
6 | 函数结束 | nums = [3,1,2] | - | - | - | 返回修改后的数组 |
my code is right.