189. Rotate Array

来源:互联网 发布:ospf使用的算法 编辑:程序博客网 时间:2024/06/07 13:05

题目来源【Leetcode】

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].

方法一:往前插入

class Solution {public:    void rotate(vector<int>& nums, int k) {        if(k != 0 && nums.size()!=0){            int i = 0;           while(i < k){               nums.insert(nums.begin(),nums[nums.size()-1]);               nums.pop_back();               i++;           }        }    }};

方法二:直接进行移动:

class Solution {public:    void rotate(vector<int>& nums, int k) {        int n = nums.size();        if(k > 0 && n !=0){          vector<int>temp(nums);          for(int i = 0; i < n; i++){              nums[(i+k)%n] = temp[i];          }        }    }};
原创粉丝点击