Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
1. Divide the array two parts: 1,2,3,4 and 5, 6
2. Reverse first part: 4,3,2,1,5,6
3. Reverse second part: 4,3,2,1,6,5
4. Reverse the whole array: 5,6,1,2,3,4
Only 12 digits and a long goes up to about 19 digits.java EmptyDemo
1461336494758
1461336494759
1461336494764
Campbell Ritchie wrote:Calling current time millis: 1ms. 1000000 iterations of empty loop: 5ms. Take off time for milliseconds call, and you get 4ms per 1000000 loops. That is 4ns per iteration. Isn't your life enriched by knowing that
dhrubo bhattacharjee wrote:I have implemented the solution using two different methods:
The first method(my initial solution) rotateArray1 is very straightforward where we divide the array into two parts and then copy the elements back into the main array.
I found the logic for the second method in programcreek which says :
1. Divide the array two parts: 1,2,3,4 and 5, 6
2. Reverse first part: 4,3,2,1,5,6
3. Reverse second part: 4,3,2,1,6,5
4. Reverse the whole array: 5,6,1,2,3,4
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
Winston Gutkowski wrote:I'd say that the two styles are likely to be about the same in terms of speed (O(2n)), but the second is better in terms of space, since it can be done in place.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
There are three kinds of actuaries: those who can count, and those who can't.
Piet Souris wrote:O(n) and O(2n) are both O(n).
Well in fact there are many methods. The easiest I can think of is:...
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |