LeetCode 189. Rotate Array

2022. 7. 8. 00:31STUDY/LeetCode

반응형

Given an array, rotate the array to the right by 'k' steps, where 'k' is non-negative.

Ex 1)

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Ex 2)

Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation: 
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]

 

Solution )

void rotate(int* nums, int numsSize, int k)
{
	size_t tmp;
	size_t i;
	for(i = 0; i < numsSize / 2; i++)
	{
		// reverse array
		tmp = nums[i];
		nums[i] = nums[numsSize - i - 1];
		nums[numsSize - i - 1] = tmp;
	}	    
	 
	k %= numsSize;
    
	for(i = 0; i < k / 2; i++)
	{
		// reverse first k elements
		tmp = nums[i];
		nums[i] = nums[k - i - 1];
		nums[k - i - 1] = tmp;
	}

	for(i = k; i < (numsSize - k) / 2 + k ; i++)
	{
		// reverse last (numsSize - k) elements
		tmp = nums[i];
		nums[i] = nums[numsSize - i + k - 1];
		nums[numsSize - i + k - 1] = tmp;
	}
}

허어얼러러러러러ㅓㄹㄹ ㄹ

ㅠㅠ 

다시 ㅈ풀어보쟈구.... ! 

The other

void swap(int *a, int *b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

void rotate_array(int* begin, int* end)
{
    while(begin < end) {
        swap(begin++, --end);
    }
}

void rotate(int* nums, int numsSize, int k)
{
    k = numsSize - k % numsSize;
    rotate_array(nums, nums + k);
    rotate_array(nums + k, nums + numsSize);
    rotate_array(nums, nums + numsSize);
}

 

728x90
반응형