关闭

LeetCode Rotate Array

标签: javaleetcode
118人阅读 评论(0) 收藏 举报
分类:

Description:

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.

Solution:

有这么几种方法:

1. 重新new一个数组

2. 向右循环k次

3. 比较巧妙。将数组分为两个部分,前面n-k个和后面的k个,下标分别是[0, n-k-1]和[ n-k, n-1]。然后前后两个区间都分别倒置,最后再将整个区间倒置。

import java.util.*;

public class Solution {
	public void rotate(int[] nums, int k) {
		int n = nums.length;
		k = k % n;
		reverse(nums, 0, n - k - 1);
		reverse(nums, n - k, n - 1);
		reverse(nums, 0, n - 1);
	}

	void reverse(int[] nums, int start, int end) {
		int c;
		for (int i = start, j = end; i < j; i++, j--) {
			c = nums[i];
			nums[i] = nums[j];
			nums[j] = c;
		}
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:62461次
    • 积分:3260
    • 等级:
    • 排名:第10448名
    • 原创:288篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    最新评论