189. Rotate Array
- Get link
- X
- Other Apps
Intuition
we can solve it by finding the right possition for each elements
Approach
first find mod of k with length of array, than we have to reverse a array only 3 times first from whole than 0 to k-1 and lastly from k to last index
Complexity
- Time complexity:O(n)
- Space complexity:O(1)
Code
Java
class Solution {
public void rotate(int[] nums, int k) {
k %= nums.length;
// for(int i =0; i<k; i++){
// int temp = nums[nums.length-1];
// for(int j =nums.length-1 ; j>0;j--){
// nums[j] = nums[j-1];
// }
// nums[0] = temp;
// }
reverse(nums, 0, nums.length-1);
reverse(nums, 0, k-1);
reverse(nums, k, 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--;
}
}
}- Get link
- X
- Other Apps
Comments
Post a Comment