码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 189 Rotate Array

时间:2015-02-25 06:55:51      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

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.

[show hint]

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

 

解题思路:

几天没回来刷题结果Leetcode又出新题了。。真的是刷不完的节奏了吗。。。

我的思路是copy给的array两遍, 比如{1, 2, 3, 4, 5, 6, 7}就变成了{1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7} (跟亚麻他们家OA的那道right rotation差不多思路)

然后找到k该开始的那个点, 比如 k = 3, 就是从index = nums.length - k开始的~从那开始往后截取就行啦~~~

 

注意的是: k有可能是nums长度的各种各种倍, 比如100多倍这样子, 所以要取余~

 

 1 public void rotate(int[] nums, int k) {
 2         k = k % nums.length;
 3         int[] temp = new int[nums.length * 2];
 4         for(int i = 0; i < nums.length; i++){
 5             temp[i] = nums[i];
 6             temp[i + nums.length] = nums[i];
 7         }
 8         int res = nums.length - k;
 9         for(int i = 0; i < nums.length; i++){
10             nums[i] = temp[res];
11             res++;
12         }
13     }

 

Leetcode 189 Rotate Array

标签:

原文地址:http://www.cnblogs.com/sherry900105/p/4299110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!