赞
踩
给你一个数组,将数组中的元素向右轮转 k
个位置,其中 k
是非负数。
输入: nums = [1,2,3,4,5,6,7], k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右轮转 1 步: [7,1,2,3,4,5,6]
向右轮转 2 步: [6,7,1,2,3,4,5]
向右轮转 3 步: [5,6,7,1,2,3,4]
输入:nums = [-1,-100,3,99], k = 2
输出:[3,99,-1,-100]
解释:
向右轮转 1 步: [99,-1,-100,3]
向右轮转 2 步: [3,99,-1,-100]
- class Solution {
- private void reverse(int[] nums, int start, int end) {
- for (int i = start, j = end; i < j; i++, j--) {
- int temp = nums[j];
- nums[j] = nums[i];
- nums[i] = temp;
- }
- }
- public void rotate(int[] nums, int k) {
- int n = nums.length;
- k %= n;
- reverse(nums, 0, n - 1);
- reverse(nums, 0, k - 1);
- reverse(nums, k, n - 1);
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。