189. Rotary Arrays – LeetCode (leetcode-cn.com)

There’s only one way we can do this. This method is not only practical, but also can very well avoid the problem of space complexity is too high.

Commonly used ideas: three – step reversal method

This method is a great person thought out, why is it called the three-step flip method? Because when we’re doing this type of problem, we’re going to flip it three times, so for this problem, let’s say we have 10 elements in arR, and we’re going to rotate it k times to the right, so we just have to invert the last k elements of arR, invert the first n minus k elements, and then invert the entire array, The final result is the result of rotating the array k times to the right.

Example code is as follows:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>              
//printf
void turn_right(int arr[], int left, int right)
{
	while (left < right)
	{
		arr[left] = arr[left] ^ arr[right];         //a=a^b
		arr[right] = arr[right] ^ arr[left];      //b=b^a
		arr[left] = arr[left] ^ arr[right];        //a=a^b
		// Content exchange between left and rightleft++; right--; }}void print(int arr[], int sz)
{
	for (int i = 0; i < sz; i++)
	{
		printf("%d ", arr[i]);
	}
}

int main()
{
	int k = 0;
	printf("Enter the value of k to rotate k elements to the right: \n");
	scanf("%d", &k);
	// Enter the value k to rotate k elements to the right
	int arr[] = { 1.2.3.4.5.6.7 };
	int sz = sizeof(arr) / sizeof(arr[0]);
	if (k >= sz)
	{
		k = k % sz;
		// When k is greater than or equal to sz, the number of elements rotated to the right is the value of k%sz.
	}
	turn_right(arr, sz - k , sz - 1);
	// invert k
	turn_right(arr, 0, sz - k - 1);
	// sz-k = sz-k
	turn_right(arr, 0, sz - 1);
	// Invert the entire array

	print(arr, sz);
	// Prints the array

	return 0;
}
Copy the code

Output result:

This idea can provide us with a way of thinking in the future, and this method is not limited to integer arrays, we have to say that the founder of this method is really powerful.


This is the end of the introduction of this topic, if you think this article is more or less helpful to you, you can click a like or a wave of support oh, welcome to the big guy criticism, let’s see you next time!