LeetCode Rotate Array

来源:互联网 发布:js判断是否为质数 编辑:程序博客网 时间:2024/06/06 19:44

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
原创粉丝点击