zoukankan      html  css  js  c++  java
  • [leetcode-189-Rotate Array]

    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.

    思路:

    需要一个临时数组储存原数据,然后先取后k个元素放到结果数组前边,再将原数据其余元素放到结果数组后边。

    void rotate(vector<int>& nums, int k)
        {
            if (k <= 0 || k%nums.size() == 0)return;
            vector<int>temp = nums;    
            int size = nums.size();
            k %=size;
            int i = 0;
            for (int j = size - k; i < k;j++)
            {
                nums[i++] = temp[j];
            }
            for (int j = 0; j < size - k;j++)
            {
                nums[i++] = temp[j];
            }
        }
  • 相关阅读:
    Hashmap实现原理
    策略模式
    Google Drive ubuntu
    numix Docky
    Google Drive 和 Dropbox 同步同一个文件夹目录
    sublime text 2
    matlab cell
    liteide
    taglist and nerdtree
    codeblocks
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6673799.html
Copyright © 2011-2022 走看看