leetcode - 189. 旋转数组

栏目: 编程工具 · 发布时间: 6年前

/**
	 * 旋转数组:将数组的后 k 位数移至头部,前 length - k 位数移至尾部
	 * 要求使用原地算法,即不使用额外的空间
	 * @param nums 数组
	 * @param k 旋转的个数
	 */
	private static void rotate(int[] nums, int k) {
		int length = nums.length;
		// 无须操作
		if (k == 0 || k == length || length == 1) {
			return;
		}
		// 修正 k
		if (k > length) {
			k %= length;
		}
		// 从 length - 1 开始操作
		int indexLimit = length - 1;
		int curIndex = indexLimit;
		int lastIndex = indexLimit;
		int lastValue = nums[indexLimit];
		int count = 0;
		while (count++ < length) {
			curIndex += k;
			// 修正 curIndex
			if (curIndex > indexLimit) {
				curIndex -= length;
			}
			int tmp = nums[curIndex];
			nums[curIndex] = lastValue;
			lastValue = tmp;
			if (curIndex == lastIndex) {
				// 一次完整的迭代交换后
				// 需要重置索引和 lastValue
				curIndex = --lastIndex;
				lastValue = nums[curIndex];
			}
		}
	}
复制代码

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Python基础教程(第2版)

Python基础教程(第2版)

Magnus Lie Hetland / 司维、曾军崴、谭颖华 / 人民邮电出版社 / 2010-7 / 69.00元

本书是经典教程的全新改版,作者根据Python 3.0版本的种种变化,全面改写了书中内容,做到既能“瞻前”也能“顾后”。本书层次鲜明、结构严谨、内容翔实,特别是在最后几章,作者将前面讲述的内容应用到了10个引人入胜的项目中,并以模板的形式介绍了项目的开发过程。本书既适合初学者夯实基础,又能帮助Python程序员提升技能,即使是 Python方面的技术专家,也能从书里找到令你耳目一新的东西。一起来看看 《Python基础教程(第2版)》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

html转js在线工具
html转js在线工具

html转js在线工具