问题:

给定一个数组,要求向左或向右循环移动k位

如 1,2,3,4,5,6,7,8,9 向左循环移动移动3位变成4,5,6,7,8,9,1,2,3

 

答案:

1. 反转数组

 

reverse(v.begin(), v.begin() + k);

reverse(v.begin() + k, v.end());

reverse(v.begin(), v.end());

 

2. 最大公约数

int gcd(int m, int n)

{

     return n == 0? m : gcd(n, m  % n);

}

 

void rotate(char* data, size_t count, int k)

{

     size_t d = gcd(count, k);

     for(int i  = 0; i < d; i++)

     {

          size_t cur_pos = i;

          size_t prev_pos = cur_pos;

          char temp = data[cur_pos];

          while((prev_pos = (prev_pos + k) % count ) != i)

          {

               data[cur_pos] = data[prev_pos];

               cur_pos = prev_pos;

          }

          data[cur_pos] = temp;

     }

}     

 

3 模拟STL的rotate

void rotate(char* data, size_t count, int k)

{

     int next = k;

     int first = 0;

     while(first != next)

     {

          data[first++] == data[next++];

          if(next == count)

          {

               next = k;

          }

          else if(first == k)

          {

               k = next;

          }

     }

}

posted on 2008-10-26 13:48  哈哈熊  阅读(527)  评论(0编辑  收藏  举报