第二周LeetCode

来源:互联网 发布:ug电极自动编程 编辑:程序博客网 时间:2024/06/05 08:57

Rotate Array

题目
难度 Easy
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

实现思路
这次题目利用了stl模板的便利,代码比较短,每次就是把尾部的元素pop掉,然后插入到头部。复杂度为k乘以vector的insert算法的复杂度(即O(n),因为k比n小,所以复杂度为O(n)。同样的思路可以用栈和链表做,没有限定参数列表的话,链表的复杂度最低,因为pop_ back()和push_front()的复杂度都为O(1)。

代码

void rotate(vector<int>& nums, int k) {        int temp;        for (int i = 0; i < k; i++) {            temp = *(nums.rbegin());            nums.pop_back();            auto it = nums.begin();            nums.insert(it, temp);        }    }//若用链表void rotate(list<int> &nums, int k) {        int temp ;        for (int i = 0; i < k; i++) {            temp = nums.back();            nums.pop_back();             nums.push_front(temp);        }    }