Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
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]
Brute Force: O(n*k) where n is length of array
public void Rotate(int[] nums, int k) {
if(nums.Length<k){
k=k%nums.Length;
}
for(int j =0;j<k;j++){
for(int i=nums.Length-1;i>0;i--){
int temp= nums[i];
nums[i]=nums[i-1];
nums[i-1]=temp;
}
}
}
Better Solution 2: Time: O(n) where n is length of array Space: O(n)
public void Rotate(int[] nums, int k)
{
if (nums.Length < k)
{
k = k % nums.Length;
}
if (k == 0)
{
return;
}
int[] temp = new int[nums.Length];
int i = 0;
for (int j = nums.Length - k; i < nums.Length; j++)
{
temp[i] = nums[j];
if (j == nums.Length - 1)
{
j = -1;
}
i++;
}
for (int h = 0; h < nums.Length; h++)
{
nums[h] = temp[h];
}
}
Solution 3: Time: O(n) where n is length of array
Space: O(1)
public void Rotate(int[] nums, int k) {
if(nums.Length<k)
{
k=k%nums.Length;
}
if(k==0 || k==nums.Length)
{
return;
}
reverse(nums,nums.Length-k,nums.Length-1);
reverse(nums,0,nums.Length-k-1);
reverse(nums,0,nums.Length-1);
}
public void reverse(int[] nums,int start,int end)
{
while(start<end)
{
int temp=nums[start];
nums[start]=nums[end];
nums[end]=temp;
start++;
end--;
}
}
Solution 3: Time: O(n) where n is length of array
Space: O(1)
if(nums.Length<k)
{
k=k%nums.Length;
}
if(k==0 || k==nums.Length)
{
return;
}
reverse(nums,nums.Length-k,nums.Length-1);
reverse(nums,0,nums.Length-k-1);
reverse(nums,0,nums.Length-1);
}
public void reverse(int[] nums,int start,int end)
{
while(start<end)
{
int temp=nums[start];
nums[start]=nums[end];
nums[end]=temp;
start++;
end--;
}
}
No comments:
Post a Comment