Algorithm to rotate an array in linear time

后端 未结 22 2087
我寻月下人不归
我寻月下人不归 2020-11-28 05:05

How to rotate an integer array by i times using swap function only in linear time.

22条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 05:55

    Simple Solution in O(n) time and using O(1) space:
    for e.g 1,2,3,4,5,6,7
    rotating 2 times 
    start with index 2, store a[0] as last
    Iteration 1: 1,2,1,4,3,6,5 (1-->3-->5-->7)
    Iteration 2: 1,7,1,2,3,4,5 (2-->4-->6)
    replace 1 with 6 (last value).
    
    public int[] roatateArray(int[] a,int k)
    {
        int last = a[0];
        int start = k;
        for(int j=0;j

提交回复
热议问题