1
0

More than 3 years have passed since last update.

アルゴリズム体操7

Last updated at Posted at 2019-12-21

Move zeros to left

説明

一つの整数型の配列が渡されます。
配列内の他の要素の順序を維持しながら、0に等しいすべての要素を左に移動させるアルゴリズムを実装しましょう。
次の整数配列を見てみましょう。

Screen Shot 2019-12-20 at 17.42.26.png

すべての0に等しい要素を左に移動すると、配列は次のようになります。(0以外の要素の順序を維持する必要があります)

Screen Shot 2019-12-20 at 17.44.09.png

Solution

Runtime Complexity O(n)

0の要素を配列から探す必要があります。

Memory Complexity O(1)

二つのポインター(反復子)を使うことで渡された配列のみで実装できます。

アルゴリズムの主な流れは

  1. 2つのマーカーread_index と write_indexを配列の最後の要素に配置させます。Screen Shot 2019-12-20 at 17.57.38.png

  2. read_index が 0 以上の間に

  3. read_indexが「0」を指している場合は read_indexのみを減少させる。Screen Shot 2019-12-20 at 17.58.40.png
    Screen Shot 2019-12-20 at 17.59.16.png
    read_indexがゼロ以外を指す場合、write_indexにread_indexの要素を書き込み、write_indexとread_index の両方を減少。Screen Shot 2019-12-20 at 17.59.59.png

  4. read_indexが-1になり、ループを抜けて、現在のwrite_indexから0まで配列の要素を0にアサインしていく。
    Screen Shot 2019-12-20 at 18.02.31.png
    Screen Shot 2019-12-20 at 18.03.14.png

  5. 完成
    Screen Shot 2019-12-20 at 18.03.32.png

実装

moveZeroToLeft.java
public class moveZerosToLeft {
    public void move_zeros_to_left_in_array(int[] A) {

        int readIndex = A.length - 1;
        int writeIndex = A.length -1;

        while (readIndex >= 0) {

            if (A[readIndex] != 0) {
                A[writeIndex] = A[readIndex];
                writeIndex--;
            }
            readIndex--;
        }

       while (writeIndex >= 0) {
           A[writeIndex] = 0;
           writeIndex--;
       }
    }
}
Mina.java
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {
        // write your code here
        moveZerosToLeft algorithm = new moveZerosToLeft();

        int[] v = new int[]{1, 10, -1, 11, 5, 0, -7, 0, 25, -35};
        System.out.println("Original Array: " + Arrays.toString(v));
        algorithm.move_zeros_to_left_in_array(v);
        for (int item : v) {
            System.out.print(item + ", ");
        }
    }
}

Output

Screen Shot 2019-12-20 at 18.06.27.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0