leetCode 189. Rotate Array 数组

简介:

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位,多出来的移到数组前面。

思路:

用一个新数组来替换它即可。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class  Solution {
public :
     void  rotate(vector< int >& nums,  int  k) {
         if (k == 0 || nums.size() == 1 || nums.size() == 0)
             return ;
         if (k > nums.size())
             k = k % nums.size();
         int  i,count;
         count = 0;
         i = nums.size() - k;
         vector< int > tmp;
         while (count != nums.size() )
         {
             if (i >= nums.size() )
             {
                 i -= nums.size();
             }
             tmp.push_back(nums[i]);
             i++;
             count++;
         }
         
         nums.swap(tmp);
     }
};



本文转自313119992 51CTO博客,原文链接:http://blog.51cto.com/qiaopeng688/1837128

相关文章
|
5天前
|
C++ Python
二刷力扣--数组
二刷力扣--数组
|
6天前
【LeetCode刷题】前缀和解决问题:742.寻找数组的中心下标、238.除自身以外数组的乘积
【LeetCode刷题】前缀和解决问题:742.寻找数组的中心下标、238.除自身以外数组的乘积
|
6天前
【LeetCode刷题】二分查找:寻找旋转排序数组中的最小值、点名
【LeetCode刷题】二分查找:寻找旋转排序数组中的最小值、点名
|
6天前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
|
6天前
|
算法
【经典LeetCode算法题目专栏分类】【第10期】排序问题、股票问题与TOP K问题:翻转对、买卖股票最佳时机、数组中第K个最大/最小元素
【经典LeetCode算法题目专栏分类】【第10期】排序问题、股票问题与TOP K问题:翻转对、买卖股票最佳时机、数组中第K个最大/最小元素
|
6天前
|
算法
【经典LeetCode算法题目专栏分类】【第6期】二分查找系列:x的平方根、有效完全平方数、搜索二位矩阵、寻找旋转排序数组最小值
【经典LeetCode算法题目专栏分类】【第6期】二分查找系列:x的平方根、有效完全平方数、搜索二位矩阵、寻找旋转排序数组最小值
|
9天前
|
存储 算法 数据可视化
深入解读力扣154题:寻找旋转排序数组中的最小值 II(多种方法及详细ASCII图解)
深入解读力扣154题:寻找旋转排序数组中的最小值 II(多种方法及详细ASCII图解)
|
9天前
|
存储 算法 数据可视化
|
9天前
|
存储 传感器 算法
LeetCode题目89:格雷码 递归、迭代及位操作在数组合并中的应用
LeetCode题目89:格雷码 递归、迭代及位操作在数组合并中的应用
|
9天前
|
存储 算法 数据挖掘
LeetCode 题目 81:搜索旋转排序数组 II
LeetCode 题目 81:搜索旋转排序数组 II