听别人说起面试的时候考了这个,网上随便搜了下,有两种比较笨的方法,一种是创建一个新的数组,把旧的数组中的数放到新数组的移位后的位置,空间复杂度是O(n);另一种是每次移一位,虽然空间复杂度是O(1),但时间复杂度是O(k*n)。
我自己也写了个,感觉比上面两种好一些,时间复杂度是O(n),空间复杂度是常数:
首先把0位置的值移到相应位置,假设是i;再将i位置的值移到相应位置,假设是k,依次下去,一共是移动n次。方便起见,用数字代替字符串。
- public class Shift {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- int array[] = {0, 1, 2, 3, 4};
- int k = 3 % array.length;
- int lastValue = array[0];
- int pos = 0;
- for(int i = 0; i < array.length; i++){
- int newpos = (pos + array.length - k) % array.length;
- int temp = lastValue;
- lastValue = array[newpos];
- array[newpos] = temp;
- pos = newpos;
- }
- for(int i : array){
- System.out.print( i + " ");
- }
- }
- }
转载于:https://blog.51cto.com/jianshusoft/693812