轮转数组 - 中等

*************

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.

步骤当前执行代码行变量状态变化条件判断循环迭代输出内容操作注释
1void rotate(...)nums = [1,2,3], k = 1---进入函数
2int n = nums.size()n = 3 (原数组长度)---获取数组长度
3if (k > n)k(1) ≤ n(3) → false不执行if块--检查k是否需要取模
4nums.insert(...)nums = [1,2,3] → [3,1,2,3]---插入后k个元素到开头
5nums.erase(...)nums = [3,1,2,3] → [3,1,2]---删除最后k个元素
6函数结束nums = [3,1,2]---返回修改后的数组

my code is right.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值