听别人说起面试的时候考了这个,网上随便搜了下,有两种比较笨的方法,一种是创建一个新的数组,把旧的数组中的数放到新数组的移位后的位置,空间复杂度是O(n);另一种是每次移一位,虽然空间复杂度是O(1),但时间复杂度是O(k*n)。

  我自己也写了个,感觉比上面两种好一些,时间复杂度是O(n),空间复杂度是常数:

  首先把0位置的值移到相应位置,假设是i;再将i位置的值移到相应位置,假设是k,依次下去,一共是移动n次。方便起见,用数字代替字符串。

 

  1. public class Shift { 
  2.  
  3.     /** 
  4.      * @param args 
  5.      */ 
  6.     public static void main(String[] args) { 
  7.         // TODO Auto-generated method stub 
  8.         int array[] = {01234}; 
  9.         int k = 3 % array.length
  10.          
  11.         int lastValue = array[0]; 
  12.         int pos = 0
  13.          
  14.         for(int i = 0; i < array.length; i++){ 
  15.             int newpos = (pos + array.length - k) % array.length; 
  16.             int temp = lastValue; 
  17.             lastValue = array[newpos]; 
  18.             array[newpos] = temp; 
  19.             pos = newpos; 
  20.         } 
  21.          
  22.          
  23.         for(int i : array){ 
  24.             System.out.print( i + " "); 
  25.         } 
  26.          
  27.     } 
  28.