4 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
我認(rèn)為這與就地旋轉(zhuǎn)陣列一樣有效。適用于左右旋轉(zhuǎn),具體取決于 的符號(hào)rotateBy:
private static void Rotate<T>(T[] array, int rotateBy)
{
rotateBy %= array.Length;
// Nothing to do?
if (rotateBy == 0)
return;
// Normalize it to a right rotation
if (rotateBy < 0)
rotateBy = array.Length + rotateBy;
// Allocate the smallest possible temp array
if (rotateBy > array.Length / 2)
{
T[] temp = new T[array.Length - rotateBy];
Array.Copy(array, 0, temp, 0, array.Length - rotateBy);
Array.Copy(array, array.Length - rotateBy, array, 0, rotateBy);
Array.Copy(temp, 0, array, rotateBy, array.Length - rotateBy);
}
else
{
T[] temp = new T[rotateBy];
Array.Copy(array, array.Length - rotateBy, temp, 0, rotateBy);
Array.Copy(array, 0, array, rotateBy, array.Length - rotateBy);
Array.Copy(temp, 0, array, 0, rotateBy);
}
}

TA貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是作弊,但 LINQ 解決方案可能是:
var array = Enumerable.Range(0, 100).ToArray();
var shiftBy = 2;
var shifted = array.Skip(shiftBy).Concat(array.Take(shiftBy)).ToArray();
如果您的任務(wù)只是以這種轉(zhuǎn)換的方式“查看”數(shù)組,為避免創(chuàng)建新數(shù)組,請(qǐng)排除末尾.ToArray()并直接迭代IEnumerable<int>。

TA貢獻(xiàn)1806條經(jīng)驗(yàn) 獲得超5個(gè)贊
使用具有輪班數(shù)量大小的旋轉(zhuǎn)緩沖區(qū)使其工作。
static void ShiftLeft(int[] array, int shifts)
{
int length = array.Length;
int actualShifts = shifts % length;
if (actualShifts == 0) return;
int[] buffer = new int[actualShifts];
Array.Copy(array, buffer, actualShifts);
int indexAddition = actualShifts - (length % actualShifts);
for (int i = length - 1; i >= 0; i--)
{
int current = array[i];
int bufferIndex = (i + indexAddition) % actualShifts;
array[i] = buffer[bufferIndex];
buffer[bufferIndex] = current;
}
}
編輯:正如@canton7 所指出的,循環(huán)緩沖區(qū)增加了不必要的復(fù)雜性。下面應(yīng)該做,基本上是@canton7 的答案,盡管@canton7 由于緩沖區(qū)較小,他的答案仍然更有效:
int length = array.Length;
int actualShifts = shifts % length;
if (actualShifts == 0) return;
int[] buffer = new int[actualShifts];
Array.Copy(array, buffer, actualShifts);
Array.Copy(array, actualShifts, array, 0, length - actualShifts);
Array.Copy(buffer, 0, array, length - actualShifts, actualShifts);

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超3個(gè)贊
import java.util.*;
public class ArrayRotation{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("enter size of array:");
int n=sc.nextInt();
int arr[]=new int[n];
System.out.println("enter elements:");
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
System.out.println("enter shifts:");
int d=sc.nextInt();
int arr1[]=new int[d];
for(int i=0;i<d;i++)
arr1[i]=arr[i];
System.out.println("Array after rotating");
for(int i=d;i<n;i++)
System.out.print(arr[i]+" ");
for(int i=0;i<d;i++)
System.out.print(arr1[i]+" ");
}
}
- 4 回答
- 0 關(guān)注
- 158 瀏覽
添加回答
舉報(bào)