2016-10-03 4 views
1

HackerRankの問題「配列:左回転」のための最適化されたソリューションを見つけるために、整数の配列にintプリミティブの配列を変換し、メソッド。コレクション。 最初の行で、ユーザは n =整数の数を入力し、k =左回転の数 を入力し、2行目にスペースで区切られた整数を入力します。それは次の入力でテストしたとき大規模な配列の配列では、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

こんにちは、エラン、I未削除の問題、それを編集するためのおかげで。 –

答えて

1

Collections.rotate()が右に回転しています。これが最初の問題です。第二の問題は、ループ内でkで回っているので、k*k回を合計していることです。あなただけ(ないループで)これを実行する必要があります。

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

+0

ありがとう、あなたのソリューションは問題を解決しました! –

関連する問題