Given an array, rotate the array to the right by k steps
Example 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]
Approach:
Java
import java.util.Arrays;
public class RotateArrayKthTime {
public static void main(String[] args) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7 };
int k = 3;
rotate(nums, k);
System.out.println(Arrays.toString(nums));
}
public static void rotate(int[] nums, int k) {
for (int i = 0; i < k; i++) {
int tmp = nums[nums.length - 1];
for (int j = nums.length - 1; j > 0; j--) {
nums[j] = nums[j - 1];
}
nums[0] = tmp;
}
}
}
C++
#include <bits/stdc++.h>
using namespace std;
void rotate(int nums[], int n, int k)
{
for (int i = 0; i < k; i++)
{
int tmp = nums[n - 1];
for (int j = n - 1; j > 0; j--)
{
nums[j] = nums[j - 1];
}
nums[0] = tmp;
}
}
int main()
{
int nums[] = { 1, 2, 3, 4, 5, 6, 7 };
int k = 3;
int n=sizeof(nums)/sizeof(nums[0]);
rotate(nums, n,k);
for(int i=0;i<n;i++)
cout<<nums[i]<<" ";
return 0;
}
No comments:
Post a Comment