数组元素循环右移问题PTA
时间: 2023-12-26 13:26:26 浏览: 126
C语言数组元素循环右移问题及解决方法
5星 · 资源好评率100%
以下是C语言和Python两种实现数组元素循环右移问题的例子:
C语言实现:
```c
#include <stdio.h>
void reverse(int arr[], int start, int end) {
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
void rightShift(int arr[], int n, int k) {
k %= n;
reverse(arr, 0, n - k - 1);
reverse(arr, n - k, n - 1);
reverse(arr, 0, n - 1);
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
rightShift(arr, n, k);
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
if (i != n - 1) {
printf(" ");
}
}
return 0;
}
```
Python实现:
```python
nums = input()
L = nums.split(" ")
A, B = int(L[0]), int(L[-1])
B = B % A
numChars = input().split(" ")
Array = [int(i) for i in numChars]
if B > 0:
Array = Array[::-1]
leftA = Array[:B][::-1]
rightA = Array[B:][::-1]
Array = leftA + rightA
length = len(Array)
for i in range(length):
print(Array[i], end="")
if i < (length - 1):
print(" ", end="")
i = i + 1
```
阅读全文