An Algorithm for rotating a sequence
An algorithm for rotating a sequence
I attended a job interview today, the interviewer asks me a question about how to rotate a sequence with a good space efficiency.
I believe I give him a terrible answer. And the interviewer gives me his answer, well, thanks him a lot.
So how to rotate a sequence? There is a sequence blow?
I wrote a sample code and upload into GitHub. Maybe I should add this algorithm into all my sequence related classes.
I believe I give him a terrible answer. And the interviewer gives me his answer, well, thanks him a lot.
So how to rotate a sequence? There is a sequence blow?
+--+--+--+--+--+--+--+--+ | 1| 2| 3| 4| 5| 6| 7| 8| +--+--+--+--+--+--+--+--+then rotate the sequence to left by 3? what we get is as following.
+--+--+--+--+--+--+--+--+ | 4| 5| 6| 7| 8| 1| 2| 3| +--+--+--+--+--+--+--+--+So the following step to step tutorial is a space efficiency way.
- reverse the first 3 sequence.
- reverse the last (8 - 3) = 5 sequence.
- reverse the whole sequence.
orignal sequence
n=3
+--+--+--+--+--+--+--+--+
| 1| 2| 3| 4| 5| 6| 7| 8|
+--+--+--+--+--+--+--+--+
step 1. reverse first n sequence
+--+--+--+--+--+--+--+--+
| 3| 2| 1| 4| 5| 6| 7| 8|
+--+--+--+--+--+--+--+--+
step 2. reverse last sequence
+--+--+--+--+--+--+--+--+
| 3| 2| 1| 8| 7| 6| 5| 4|
+--+--+--+--+--+--+--+--+
step 3. reverse the whole sequence
+--+--+--+--+--+--+--+--+
| 4| 5| 6| 7| 8| 1| 2| 3|
+--+--+--+--+--+--+--+--+
I wrote a sample code and upload into GitHub. Maybe I should add this algorithm into all my sequence related classes.
Comments
Post a Comment