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. CCKiller:Linux轻量级CC攻击防御工具,秒级检查、自动拉黑和释放 《CCKiller:Linux轻量级CC攻击防御工具,秒级检查、自动拉黑和释放》来自张戈博客

    张戈博客很久以前分享过一个CC攻击的防御脚本,写得不怎么样,不过被51CTO意外转载了.博客从此走上了经常被人拿来练手的不归之路. 当然,还是有不少朋友在生产环境使用,并且会留言询问相关问题.根据这些 ...

  2. SPI协议介绍

    一.概述 SPI, Serial Perripheral Interface, 串行外围设备接口, 是 Motorola 公司推出的一种同步串行接口技术. SPI 总线在物理上是通过接在外围设备微控制 ...

  3. 织梦DedeCMS自定义表单提交成功后返回当前页面的教程

    织梦的自定义表单制作的留言,报名等功能,提交成功后会自动返回到首页,那么如何让它返回到当前页面呢? 方法如下: 打开plus/diy.php文件 找到 showmsg($bkmsg, $goto); ...

  4. shell 获取文件名

    1.获取文件名并修改文件名 2.$@ 遍历参数 3.赋值要加"" 4.if 判断注意空格 else后面不能跟then

  5. [转]Unity Shader 学习总结

    1.先来一段单张纹理贴图的shader示例代码: // Upgrade NOTE: replaced 'mul(UNITY_MATRIX_MVP,*)' with 'UnityObjectToClip ...

  6. 转载 【iOS开发】网页JS与OC交互(JavaScriptCore) OC ----->JS

      目标 本文介绍利用苹果在iOS7时发布的JavaScriptCore.framework框架进行js与OC的交互.我们想要达到的目标是: OC调用网页上的js方法 网页js调用APP中的OC方法 ...

  7. Spring MVC 返回Json IE出现下载

    今天在做一个利用IFrame提交进行form提交表单的时候发现返回的json在ie下竟然弹出了下载的提示, 于是就查看了返回的Content-type:appliation/json;charset= ...

  8. UIApplicationDelegate 各方法回调时机

    本篇文章主要介绍一些UIApplicationDelegate中几个常用的回调方法的调用时机.以帮助你判断哪些方法倒底放到哪个回调中去实现. 1. – (void)applicationDidFini ...

  9. 使用memcache进行账号验证服务

    适用环境是需要频繁进行账号和请求合法性验证的地方 大致思路: 1.登陆时,服务器端接收一个账号和密码,还可以再加上用户的ip等信息通过md5等加密算法计算出一个定长的字符串作为用来验证的token 2 ...

  10. 【python】-- IO多路复用(select、poll、epoll)介绍及实现

    IO多路复用(select.poll.epoll)介绍及select.epoll的实现 IO多路复用中包括 select.pool.epoll,这些都属于同步,还不属于异步 一.IO多路复用介绍 1. ...