2016-10-03 22 views
1

我嘗試爲HackerRank問題「數組:Left Rotation」找到更優化的解決方案,因此我將int基元數組轉換爲整型數組,並使用方法Collections.rotate。 在第一行,用戶輸入n =整數數,然後k =左轉數 ,在第二行,用戶輸入n個空格分隔的整數。Collections.rotate方法不適用於整數大數組

但是,當它是用下面的測試輸入:

61 48 
431 397 149 275 556 362 852 789 601 357 516 575 670 507 127 888 284 405 806 27 495 879 976 467 342 356 908 750 769 947 425 643 754 396 653 595 108 75 347 394 935 252 683 966 553 724 629 567 93 494 693 965 328 187 728 389 70 288 509 252 449 

輸出原來比預期的要有所不同。 我的代碼如下:

public class HackerRankArraysLeftRotationOptimized { 

    public static void main(String[] args) { 
    Scanner in = new Scanner(System.in); 
    int n = in.nextInt(); // the number of integers 
    int k = in.nextInt(); // the number of left rotations you must perform 
    int a[] = new int[n]; 
    for(int a_i=0; a_i < n; a_i++){ 
     a[a_i] = in.nextInt(); 
    } 

    Integer[] newArray = new Integer[a.length]; 
    int i = 0; 
    for (int value: a) { 
     newArray[i++] = Integer.valueOf(value); 
    } 

    for (int j = 0; j < k; j++) { 
     Collections.rotate(Arrays.asList(newArray), k); 
    } 

    for (int m = 0; m < newArray.length; m++) { 
     System.out.print(newArray[m] + " "); 
    } 

} 

}

有人能解釋我有什麼錯方法Collections.rotate?

+0

嗨,葉蘭,我未刪除的問題,謝謝大家編輯。 –

回答

1

Collections.rotate()正在向右旋轉,這是第一個問題。第二個問題是你在循環中旋轉k,所以你總共k*k次。你只需要做到這一點(不是在一個循環中):

Collections.rotate(Arrays.asList(newArray), -k);

+0

非常感謝,您的解決方案解決了問題! –