You may have been using Java for a while. Do you think a simple Java array question can be a challenge? Let's use the following problem to test.

Problem: 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]. How many different ways do you know to solve this problem?

Solution 1 - Intermediate Array

In a straightforward way, we can create a new array and then copy elements to the new array. Then change the original array by using System.arraycopy().

public void rotate(int[] nums, int k) {
    if(k > nums.length)
        k=k%nums.length;

    int[] result = new int[nums.length];

    for(int i=0; i < k; i++){
        result[i] = nums[nums.length-k+i];
    }

    int j=0;
    for(int i=k; i<nums.length; i++){
        result[i] = nums[j];
        j++;
    }

    System.arraycopy( result, 0, nums, 0, nums.length );
}

Space is O(n) and time is O(n). You can check out the difference between System.arraycopy() and Arrays.copyOf().

Solution 2 - Bubble Rotate

Can we do this in O(1) space?

This solution is like a bubble sort.

public static void rotate(int[] arr, int order) {
	if (arr == null || order < 0) {
	    throw new IllegalArgumentException("Illegal argument!");
	}

	for (int i = 0; i < order; i++) {
		for (int j = arr.length - 1; j > 0; j--) {
			int temp = arr[j];
			arr[j] = arr[j - 1];
			arr[j - 1] = temp;
		}
	}
}

However, the time is O(n*k).

Solution 3 – Reversal

Can we do this in O(1) space and in O(n) time? The following solution does.

Assuming we are given {1,2,3,4,5,6} and order 2. The basic idea is:

1. Divide the array two parts: 1,2,3,4 and 5, 6
2. Rotate first part: 4,3,2,1,5,6
3. Rotate second part: 4,3,2,1,6,5
4. Rotate the whole array: 5,6,1,2,3,4
public static void rotate(int[] arr, int order) {
	order = order % arr.length;

	if (arr == null || order < 0) {
		throw new IllegalArgumentException("Illegal argument!");
	}

	//length of first part
	int a = arr.length - order;

	reverse(arr, 0, a-1);
	reverse(arr, a, arr.length-1);
	reverse(arr, 0, arr.length-1);

}

public static void reverse(int[] arr, int left, int right){
	if(arr == null || arr.length == 1)
		return;

	while(left < right){
		int temp = arr[left];
		arr[left] = arr[right];
		arr[right] = temp;
		left++;
		right--;
	}
}

[算法]Rotate Array的更多相关文章

  1. LeetCode189——Rotate Array

    Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = 3, the array  ...

  2. LeetCode 189. 旋转数组(Rotate Array)

    189. 旋转数组 LeetCode189. Rotate Array 题目描述 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数. 示例 1: 输入: [1,2,3,4,5,6, ...

  3. 回文数组(Rotate Array (JS))

    旋转一个数组. function rotate(array,n){ var l =array.length,a=array.map(function(x){return x}),arr=[]; n=n ...

  4. 理解JavaScript中的参数传递 - leetcode189. Rotate Array

    1.关于leetcode 这是第一篇关于leetcode的题解,就先扯点关于leetcode的话. 其实很早前就在博客园看到过leetcode一些题解,总以为跟一般OJ大同小异,直到最近点开了一篇博文 ...

  5. Leetcode-189 Rotate Array

    #189.    Rotate Array Rotate an array of n elements to the right by k steps. For example, with n = 7 ...

  6. 【LeetCode】Rotate Array

    Rotate Array Rotate an array of n elements to the right by k steps. For example, with n = 7 and k = ...

  7. LeetCode: Reverse Words in a String && Rotate Array

    Title: Given an input string, reverse the string word by word. For example,Given s = "the sky i ...

  8. C++ STL@ list 应用 (leetcode: Rotate Array)

    STL中的list就是一双向链表,可高效地进行插入删除元素. List 是 C++标准程式库 中的一个 类 ,可以简单视之为双向 连结串行 ,以线性列的方式管理物件集合.list 的特色是在集合的任何 ...

  9. 2016.5.16——leetcode:Rotate Array,Factorial Trailing Zeroe

    Rotate Array 本题目收获: 题目: Rotate an array of n elements to the right by k steps. For example, with n = ...

随机推荐

  1. ueditor的上传存储问题

    1.使用了 http://download.csdn.net/download/ouyhong123/8520689 下载的修改版jar包.主要修改是增加了一个地址属性,ActionEnter的参数. ...

  2. 【Hadoop基础教程】4、Hadoop之完全分布式环境搭建

    上一篇blog我们完成了Hadoop伪分布式环境的搭建,伪分布式模式也叫单节点集群模式, NameNode.SecondaryNameNode.DataNode.JobTracker.TaskTrac ...

  3. shell中的括号作用

    一.小括号,圆括号() 1.单小括号 ()    ①命令组.括号中的命令将会新开一个子shell顺序执行,所以括号中的变量不能够被脚本余下的部分使用.括号中多个命令之间用分号隔开,最后一个命令可以没有 ...

  4. Unable to resolve address &#39; &#39; service &#39; &#39;: Name or service not known

    感谢朋友支持本博客,欢迎共同探讨交流,因为能力和时间有限,错误之处在所难免.欢迎指正. 假设转载,请保留作者信息. 博客地址:http://blog.csdn.net/qq_21398167 原博文地 ...

  5. Android View中getViewTreeObserver().addOnGlobalLayoutListener() (转)

    转自:Android View中getViewTreeObserver().addOnGlobalLayoutListener() 我们知道在oncreate中View.getWidth和View.g ...

  6. Spring Cloud 微服务三: API网关Spring cloud gateway

    前言:前面介绍了一款API网关组件zuul,不过发现spring cloud自己开发了一个新网关gateway,貌似要取代zuul,spring官网上也已经没有zuul的组件了(虽然在仓库中可以更新到 ...

  7. Win7系统CMD命令提示符输入中文变乱码怎么办

    Win7系统下经常使用CMD命令提示符进行很多操作,发现Win7旗舰版系统在CMD命令提示符不能输入文字,输入的中文字都变成乱码,这是怎么回事呢?本文将提供Win7系统CMD命令提示符输入中文变乱码的 ...

  8. [原创]关于absolute、relative和float的一些思考

    absolute: 元素完全脱离文档流,不占文档流的位置,不使用top.left等属性时,仍然在原文档流位置上(但是不在文档流中,也不占用位置),设置了top.left等之后,向上寻找到第一个非sta ...

  9. Kerberos Ticket管理

    Kerberos Ticket管理 本章介绍如何管理您的Kerberos Ticket,这里的Ticket是指Ticket-Granting-Ticket(TGT),是您访问集群中服务的凭证.我们假设 ...

  10. zoj 3721 Final Exam Arrangement【贪心】

    题目:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3721 来源:http://acm.hust.edu.cn/vjudg ...