[英]Rotating all elements of the array to left by “k” position but my code moves it to the right
有人可以告訴我如何解決此代碼,而不是將數組向右移動,如何使它向左移動? 有人也可以給我解釋一下嗎
public class Test {
public static void main(String[] args) {
int[] b = {10, 20, 30, 40, 50, 60};
System.out.println("\n///// Rotate Left k cell example \n////");
b = copyArray(a, a.length);
b = rotateLeft(b,4); //assuming k = 4
printArray(b); // This Should Print: { 50, 60, 10, 20, 30, 40 };
}
// Rotates all the elements of the source array to the right by 'k' positions
// Returns the updated array
public static int[] rotateLeft(int[] source, int k) {
int[] arr = copyArray(source,source.length); //copies all source to a new array
int[] temp = new int[arr.length];
for (int i = 0; i < arr.length; i++){
temp[(i + k) % arr.length] = arr[i];
}
for (int i = 0; i < arr.length; i++){
arr[i] = temp[i];
}
return arr;
}
}
因此,此代碼將元素旋轉到右側。 我應該如何修改它,使其旋轉到左側?
我得到的輸出:
{30,40,50,60,10,20}
但我想要的輸出是:
{50,60,10,20,30,40}
我認為您可以更改用於填充temp
數組的分配邏輯。 更改此行:
temp[(i + k) % arr.length] = arr[i];
對此:
temp[i] = arr[(i + k) % arr.length];
這里的邏輯是, temp[]
中的ith
條目將等於arr[]
k
ith
條目。 換句話說, temp[]
將包含左移k
的原始元素。 請注意,您仍然需要進行mod操作,以確保索引環繞數組的大小。
完整代碼:
public static int [] rotateLeft(int [] source, int k){
int arr[] = copyArray(source, source.length);
int[] temp = new int[arr.length];
for (int i=0; i<arr.length; i++) {
temp[i] = arr[(i + k) % arr.length];
}
for (int i=0; i<arr.length; i++) {
arr[i] = temp[i];
}
return arr;
}
基本上做(i - k)
而不是(i + k)
。 最重要的是,刪除copyArray
調用和第二個循環。 並且由於Java中的%
運算符會表現其行為,因此您必須在實際%
之前將source.length
添加到(i - k)
:
public static int [] rotateLeft(int [] source, int k) {
int arr[] = new int[source.length];
for (int i = 0; i < arr.length; i++){
arr[(i - k + source.length) % source.length] = source[i];
}
return arr;
}
輸出
50
60
10
20
30
40
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.