57

Java にオブジェクトの配列があり、1 つの要素を一番上に移動し、残りを 1 つ下に移動しようとしています。

サイズ 10 の配列があり、5 番目の要素を取得しようとしているとします。5 番目の要素が配置され0、0 から 5 までのすべての要素が 1 つ下にシフトされます。

このアルゴリズムは、要素を適切にシフトしません。

Object temp = pool[position];

for (int i = 0; i < position; i++) {                
    array[i+1] = array[i];
}
array[0] = temp;

正しく行うにはどうすればよいですか?

4

15 に答える 15

97

論理的には機能しないため、ループを逆にする必要があります。

for (int i = position-1; i >= 0; i--) {                
    array[i+1] = array[i];
}

または、使用することができます

System.arraycopy(array, 0, array, 1, position);
于 2011-11-01T18:15:58.857 に答える
31

Assuming your array is {10,20,30,40,50,60,70,80,90,100}

What your loop does is:

Iteration 1: array[1] = array[0]; {10,10,30,40,50,60,70,80,90,100}

Iteration 2: array[2] = array[1]; {10,10,10,40,50,60,70,80,90,100}

What you should be doing is

Object temp = pool[position];

for (int i = (position - 1); i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;
于 2011-11-01T18:20:42.077 に答える
27

あなたはただ使うことができますCollections.rotate(List<?> list, int distance)

Arrays.asList(array)に変換して使用List

詳細: https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#rotate(java.util.List,%20int)

于 2016-01-16T16:34:01.923 に答える
4

完全を期すために: Java 8 以降のストリーム ソリューション。

final String[] shiftedArray = Arrays.stream(array)
        .skip(1)
        .toArray(String[]::new);

System.arraycopy()はあなたの状況に固執したと思います。しかし、最良の長期的な解決策は、それらのコレクションが短命である限り、すべてを不変コレクション ( GuavaVavr ) に変換することかもしれません。

于 2017-10-17T14:18:57.340 に答える
2

あなたが発見したように、この方法で配列を操作するとエラーが発生しやすくなります。より良いオプションは、状況に応じてLinkedListを使用することです。リンクされたリストとすべての Java コレクションでは、配列管理は内部で処理されるため、要素の移動について心配する必要はありません。LinkedList を使用すると、呼び出すだけでremove完了addLastです。

于 2011-11-01T18:18:07.740 に答える
1

これを試して:

Object temp = pool[position];

for (int i = position-1; i >= 0; i--) {                
    array[i+1] = array[i];
}

array[0] = temp;

ここを見て動作を確認してください: http://www.ideone.com/5JfAg

于 2011-11-01T18:14:46.113 に答える
0
static void pushZerosToEnd(int arr[])
    {   int n = arr.length;
        int count = 0;  // Count of non-zero elements
        // Traverse the array. If element encountered is non-zero, then
        // replace the element at index 'count' with this element
        for (int i = 0; i < n; i++){
            if (arr[i] != 0)`enter code here`
               // arr[count++] = arr[i]; // here count is incremented
                swapNumbers(arr,count++,i);
        }
        for (int j = 0; j < n; j++){
            System.out.print(arr[j]+",");
        }
     }

    public static void swapNumbers(int [] arr, int pos1, int pos2){
        int temp  = arr[pos2];
        arr[pos2] = arr[pos1];
        arr[pos1] = temp;
    }
于 2015-09-28T18:15:47.737 に答える
0

サイズ n の配列に対する左回転操作は、配列の各要素単位を左にシフトします。これを確認してください!!!!!!

public class Solution {
    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        String[] nd = scanner.nextLine().split(" ");

        int n = Integer.parseInt(nd[0]);  //no. of elements in the array

        int d = Integer.parseInt(nd[1]);  //number of left rotations

        int[] a = new int[n]; 

      for(int i=0;i<n;i++){
          a[i]=scanner.nextInt();
      }

        Solution s= new Solution();     
//number of left rotations
        for(int j=0;j<d;j++){
              s.rotate(a,n);
        }
   //print the shifted array  
        for(int i:a){System.out.print(i+" ");}
    }

//shift each elements to the left by one 
   public static void rotate(int a[],int n){
            int  temp=a[0];
        for(int i=0;i<n;i++){
            if(i<n-1){a[i]=a[i+1];}
            else{a[i]=temp;}
      }}
}
于 2018-10-06T04:57:09.423 に答える
0
public class Test1 {

    public static void main(String[] args) {

        int[] x = { 1, 2, 3, 4, 5, 6 };
        Test1 test = new Test1();
        x = test.shiftArray(x, 2);
        for (int i = 0; i < x.length; i++) {
            System.out.print(x[i] + " ");
        }
    }

    public int[] pushFirstElementToLast(int[] x, int position) {
        int temp = x[0];
        for (int i = 0; i < x.length - 1; i++) {
            x[i] = x[i + 1];
        }
        x[x.length - 1] = temp;
        return x;
    }

    public int[] shiftArray(int[] x, int position) {
        for (int i = position - 1; i >= 0; i--) {
            x = pushFirstElementToLast(x, position);
        }
        return x;
    }
}
于 2018-01-21T18:03:03.250 に答える
0

ループの最初の繰り返しで、 の値を上書きしますarray[1]。逆の順序でインデックスを通過する必要があります。

于 2011-11-01T18:21:00.150 に答える
-1

20 個の整数の配列を作成する Java プログラムを作成し、配列を 2 つの要素で右にシフトするプロセスを実装します。

public class NewClass3 {
    
     public static void main (String args[]){
     
     int a [] = {1,2,};
    
     int temp ;
     
     for(int i = 0; i<a.length -1; i++){
      
         temp = a[i];
         a[i] = a[i+1];
         a[i+1] = temp;
     
     }
     
     for(int p : a)
     System.out.print(p);
     }
    
}
于 2016-05-12T19:01:51.887 に答える