zoukankan      html  css  js  c++  java
  • Java [Leetcode 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.

    解题思路:

    牺牲空间复杂度的话可以考虑开辟新的数组空间,然后依次移动即可;

    本方法只用一个临时变量存放临时数据,然后依次的交换数据,如图所示:

    但是注意会陷入局部循环的局面,这时将相应的下标后移一位。

    public class Solution {
        public void rotate(int[] nums, int k) {
        	int length = nums.length;
        	if(length == 0)
        		return;
        	k = k % length;
        	int head = 0, curIndex = 0, nextIndex;
        	int curValue = nums[0], nextValue;
        	for(int i = 0; i < length; i++){
        		if(curIndex == head && i > 0){ //finish a circle,move to another circle
        			curIndex++;
        			head++;
        			curValue = nums[curIndex];
        		}
        		nextIndex = (curIndex + k) % length;
        		nextValue = nums[nextIndex];
        		nums[nextIndex] = curValue;
        		curIndex = nextIndex;
        		curValue = nextValue;
        	}
        }
    }
    

      

    代码如下:

  • 相关阅读:
    php 图片剪切
    mysql 官方docker镜像使用教程
    centos7 取消自动锁屏
    nginx配置反向代理示例
    nginx 官方docker镜像使用教程
    centos 下nginx源码编译安装
    nginx rewrite规则实例讲解
    requests.session()会话保持
    我对网络IO的理解
    日常运维--rsync同步工具
  • 原文地址:https://www.cnblogs.com/zihaowang/p/5207007.html
Copyright © 2011-2022 走看看