# leetcode 189 Rotate Array

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.

1.—567旋转—765
2.—1234旋转—4321
3.—整体旋转4321765—5671234

void reverse(int left,int right,int *array)
{
int temp = 0;
while(left<right)
{

temp = array[left];
array[left]= array[right];
array[right] = temp;
left++;
right--;
}
}

void rotate(int* nums, int numsSize, int k)
{
k = k%numsSize;//不知道为何这里要加上这一句？
reverse(0,numsSize-k-1,nums);
reverse(numsSize-k,numsSize-1,nums);
reverse(0,numsSize-1,nums);
}

python解决方案：

class Solution:
# @param nums, a list of integer
# @param k, num of steps
# @return nothing, please modify the nums list in-place.
def rotate(self, nums, k):
if not nums:
return
k%=len(nums)
nums.reverse()
self.reverse(nums,0,k-1)
self.reverse(nums,k,len(nums)-1)

def reverse(self,nums,start,end):
while start<end:
nums[start],nums[end]=nums[end],nums[start]
start+=1
end-=1


|
9月前
Leetcode Find Minimum in Rotated Sorted Array 题解

32 0
|

LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
109 0
|

LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
114 0
|

LeetCode 88. 合并两个有序数组 Merge Sorted Array
LeetCode 88. 合并两个有序数组 Merge Sorted Array
90 0
|

LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
LeetCode 1013. 将数组分成和相等的三个部分 Partition Array Into Three Parts With Equal Sum
84 0
|

LeetCode 189. 旋转数组 Rotate Array
LeetCode 189. 旋转数组 Rotate Array
66 0
|
3天前
|
Python
【Leetcode刷题Python】剑指 Offer 32 - III. 从上到下打印二叉树 III

15 6
|
3天前
|
Python
【Leetcode刷题Python】剑指 Offer 26. 树的子结构

12 4
|
3天前
|

【Leetcode刷题Python】牛客. 数组中未出现的最小正整数

17 2
|
3天前
|

【Leetcode刷题Python】从列表list中创建一颗二叉树

12 7