How are you uu from CSDN, today, the content of Xiaoyalan is the rotation array, let us enter the world of rotation array
Xiao Yalan has actually written about the problem of string rotation before:
C language brushing questions (7) (string rotation problem) - "C"
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
Turn right 1 step: [7 ,1,2,3,4,5,6]
Turn right 2 steps: [6,7,1,2,3,4,5]
Turn right 3 steps: [5,6,7,1,2 ,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
Turn right 1 step: [99,-1,-100,3 ]
Turn right 2 steps: [3,99,-1,-100]
method one:
Violent solution method, rotate k times
However, the time complexity of this solution is O(N^2), and the space complexity is O(1)
Does not meet the topic requirements
So this method, Xiao Yalan does not need code to realize it
Method Two:
three-step flipping method
Original array: 1 2 3 4 5 6 7
The first nk inversions: 4 3 2 1 5 6 7
The last k inversions: 4 3 2 1 7 6 5
Overall inversion: 5 6 7 1 2 3 4
Time complexity is O(N) and space complexity is O(1)
Meet the requirements of the topic
void reverse(int* arr,int left,int right)
{
while(left<right)
{
int tmp=arr[left];
arr[left]=arr[right];
arr[right]=tmp;
left++;
right--;
}
}
void rotate(int* nums, int numsSize, int k)
{
if(k>numsSize)
{
k%=numsSize;
}
reverse(nums,0,numsSize-1-k);
reverse(nums,numsSize-k,numsSize-1);
reverse(nums,0,numsSize-1);
}
Method three:
The method of exchanging space for time
Use an extra array to put each element in the correct position
Can't use strcpy, strcpy is a function that deals with strings
void rotate(int* nums, int numsSize, int k){
if(k>numsSize)
{
k%=numsSize;
}
int*tmp=(int*)malloc(sizeof(int)*numsSize);
memcpy(tmp+k,nums,sizeof(int)*(numsSize-k));
memcpy(tmp,nums+numsSize-k,sizeof(int)*(k));
memcpy(nums,tmp,sizeof(int)*(numsSize));
free(tmp);
tmp=NULL;
}
Alright, this is the end of Xiao Yalan's round-robin array today, let's continue to do my best! ! !