# Arithmetic-Array Element Cycle Right Shift

Posted by roughie on Sun, 05 Jul 2020 17:56:48 +0200

Title: There is an integer array a whose cyclic right-shifted k-bit value requires minimum spatial complexity.
For example:
int[] a = {1,2,3,4,5,6,7}; after moving 5 bits to the right of the loop,
The values are: {3,4,5,6,7,1,2}.
The most basic implementation:

```    public void toRightMove(int[] nums, int k) {
if (k == 0 || k == nums.length) {
return;
}
int lastIndex = nums.length - 1;
int t = 0;
while (k > 0) {
t = nums[lastIndex];
for (int i = lastIndex; i > 0; i--) {
nums[i] = nums[i - 1];
}
nums = t;
k--;
}
Log.e("tag","toRightMove>>result:"+nums);
}```

The time complexity of the algorithm is O(KN), and N is the length of the array.

An example shows that there is a rule between the original array and the shifted array.By rounding it to zero, the original array is divided into two parts based on the k-value.The result is an overall replacement of the two parts.
See: Array Element Loop Right Shift Problem

This is an algorithmic topic for today's headlines, and the author's implementation is the one above.At that time, we also found this phenomenon, but for a while we didn't figure out the way to achieve it, we can only do it.So it doesn't leave much influence on the interviewer.
Code is posted here, and the efficient implementation is:

```    public void toRightMove2(int[] nums, int k) {
if(nums == null || nums.length == 0){
return;
}
k = k % nums.length;
if (k == 0 || k == nums.length) {
return;
}
int lastIndex = nums.length - 1;
int t;
for(int i = 0,j = lastIndex;i <j;i++,j --){
t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}

for(int i = 0,j = k -1;i < j;i++,j --){
t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}

for(int i = k,j = lastIndex;i < j;i++,j --){
t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
Log.e("tag","toRightMove>>result:"+nums);
}```

The time complexity decreases to O(N/2).