leetcode - 189. 旋转数组

	/**
	 * 旋转数组:将数组的后 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];
			}
		}
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章