2012-04-06 34 views
0

我有一個3的數組大小,我試圖將第一個索引轉移到最後一個位置,同時將其他索引轉移到左側。例如:轉移第一個索引

{1,2,3}到{2,3,1}

這裏是我的代碼

int[] nums = {1,2,3}; 
int[] numsShifted = new int[3]; 

for(int i = 0; i < nums.length - 1; i++) 
{ 
    int tempNum = nums[i]; 
    numsRotated[i] = nums[i + 1]; 
    numsRotated[i+1] = tempNum; 
} 

我遇到的問題是數組的最後一個索引,我得到不正確的值。謝謝。

+0

當然,你得到錯誤的資源ULT;你沒有在任何地方存儲'nums [0]'... – 2012-04-06 17:56:07

+0

是的,我發現它後,我試圖關閉帖子,但我的水平不夠高,謝謝反正。 – user1051043 2012-04-06 17:57:26

+0

@Oli Charlesworth:其實,他並不是真正覆蓋原來的陣列...... – Tudor 2012-04-06 18:04:37

回答

2

只是做一個簡單的移位,然後將第一個數字拷貝的最後一個位置:

int[] nums = {1,2,3}; 
int[] numsShifted = new int[3]; 

int temp = nums[0]; 
for(int i = 1; i < nums.length; i++) 
{ 
    numsShifted[i - 1] = nums[i]; 
} 
numsShifted[nums.length - 1] = temp; 

編輯:你實際上並不需要安全的第一個項目,因爲你沒有覆蓋原陣列。

0

那麼你需要存儲循環外的第一個元素,然後開始移位。循環結束後,只需將第一個元素存儲爲數組的最後一個元素即可。

0

您必須保存nums [0]值;

int saved = nums[0]; 

for(int i = 0; i < nums.length - 1; i++) { 
    numsShifted[i] = nums[i+1]; 
} 
numsShifted[numsShifted.length - 1] = saved; 
+0

我已經修復了代碼中的一些拼寫錯誤。 – Tudor 2012-04-06 18:01:00

0
int[] nums = {1,2,3}; 
int[] numsShifted = new int[3]; 

    for(int i = 0; i < nums.length - 1; i++) 
    { 
     int tempNum = nums[i]; //tempNum=1, tempNum=2 
     numsRotated[i] = nums[i + 1]; //numsRotated[0]=2, numsRotated[1]=3 
     numsRotated[i+1] = tempNum; //numsRotated[1]=1, numsRotated[2]=2 <- this is incorrect and the loop ends 
    } 

末,你有2,3,2。你將需要修復你的循環。

0

如果你想使用你寫的代碼,就像我一樣修復它。 否則,其他答案相當不錯!

int[] nums = {1, 2, 3}; 
    int[] numsShifted = new int[3]; 

    for (int i = 0; i < nums.length; i++) { //Do one more iteration 
     if (i + 1 > 2) { //If this is the last element, we take the first one of nums 
      numsShifted[i] = nums[0]; 
     } else { //Otherwise we do as you did in your code 
      numsShifted[i] = nums[i + 1]; 
      numsShifted[i + 1] = nums[i]; 
     }    
    } 
    System.out.println(Arrays.toString(numsShifted)); 

編輯: 刪除tempNum因爲你不需要它

0
int[] a = {1,2,3}; 
int[] b = new int[3]; 

for(int j = 0 , i = 2 ; j < a.length ; j++) 
{ 
    b[i++] = a[j]; 
    if(i >= 3) 
    i = 0; 
} 
0

這裏有一些其他的選擇,沒有循環:

public static int[] queueFirst(int[] in) { 
    int len = in.length; 
    if (len <= 1) return in; 
    int[] ret = Arrays.copyOf(Arrays.copyOfRange(in, 1, len), len); 
    ret[len - 1] = in[0]; 
    return ret; 
} 

或引用:

public static <T> T[] queueFirst(T[] in) { 
    if (in.length <= 1) return in; 
    ArrayList<T> n = new ArrayList<T>(Arrays.asList(in)); 
    n.add(n.remove(0)); 
    return n.toArray(in); 
} 
相關問題