Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

THis is what I want to do: array A[] = {1,2,3,4,5} left rotate by 2: A:{3,4,5,1,2}

do we have a simple and good solution for doing this in place? I want the array A itself to be updated with this left rotated value - with no additional space.

I tried various approaches but the logic seems different for various test cases and had a hard time finding one algorithm that fits for this seemingly simple task.

NOTE: I know this can be easily done by just creating a new array with the left rotated values. I am trying to do this in the input array itself.

Pls suggest. Simple pseudo code should do.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
241 views
Welcome To Ask or Share your Answers For Others

1 Answer

std::rotate() will do exactly what you need:

auto b = std::begin(A);
std::rotate( b, b + 2, std::end(A) );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...