C language daily practice --- rotate array

Topic description:

Given an array, rotate the elements in the array K positions to the right, where K is a non-negative number, and return the new array

Example:

Input: [1,2,3,4,5,6,7],k=3;

Output: [5,6,7,1,2,3,4]

Method 1: Using an additional array, apply for an array of the same length as the original array to put each element in the correct position.

First put the last k values ​​of the original array into the first k positions of the new array, and then put the remaining elements of the original array at the back.

void rotate(int* nums, int numsSize, int k)
{
	int* new_nums = (int*)malloc(sizeof(int) * numsSize);
	for (int i = 0; i < numsSize; i++)
	{
		new_nums[(i + k) % numsSize] = nums[i];
	}
	for (int i = 0; i < numsSize; i++)
	{
		nums[i] = new_nums[i];
	}
	free(new_nums);

Method 2: Array flip

Since we move the elements of the array to the right k times, the tail k elements will move to the head of the array, and the remaining elements will be k positions backward. Therefore, we can first flip all the elements so that the tail k elements are moved to the head of the array, and then we flip the first k elements and the rest to get the final answer.

Example:

Original array: 1 2 3 4 5 6 7

Flip all elements: 7 6 5 4 3 2 1

Flip the first k elements: 5 6 7 4 3 2 1

Then flip the remaining elements: 5 6 7 1 2 3 4

void Swap(int* a, int* b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}
void Reverse(int* nums, int start, int end)
{
	while (start < end)
	{
		Swap(&nums[start], &nums[end]);
		start += 1;
		end -= 1;
	}
}
void rotate2(int* nums, int numsSize, int k)
{
	k %= numsSize;
	Reverse(nums, 0, numsSize - 1);
	Reverse(nums, 0, k - 1);
	Reverse(nums, k, numsSize - 1);

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324216204&siteId=291194637