• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode: 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.

[show hint]

Hint:
Could you do it in-place with O(1) extra space?

Naive想法就是保存一个原数组的拷贝,然后把原数组分成前len-k个元素和后k个元素两部分,把后k个元素放到前len-k个元素前面去。这样做需要O(N)空间

in-place做法是: 

(1) reverse the array;

(2) reverse the first k elements;

(3) reverse the last n-k elements.

The first step moves the first n-k elements to the end, and moves the last k elements to the front. The next two steps put elements in the right order.

 1 public class Solution {
 2     public void rotate(int[] nums, int k) {
 3         int len = nums.length;
 4         k %= len;
 5         reverse(nums, 0, len-1);
 6         reverse(nums, 0, k-1);
 7         reverse(nums, k, len-1);
 8     }
 9     
10     public void reverse(int[] nums, int l, int r) {
11         while (l <= r) {
12             int temp = nums[l];
13             nums[l] = nums[r];
14             nums[r] = temp;
15             l++;
16             r--;
17         }
18     }
19 }

需要注意的是第4行,右移偏移量k可能比数组长度len要大,所以要先 k%=len;

posted @ 2015-03-01 05:19  neverlandly  阅读(1715)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3