3

わかりました、私はいくつかの値を持つランダムな配列を持っています:

Integer[] array = {null,null,5,111,21,null,22,null,null,null,98,25,47,null,1,23,null}

nullすべての値を、最も近い 2 つの既存の配列値の平均に置き換えたいと考えています。例: 最初の 2 つの値は、数字(になる)nullに置き換える必要があります。 5{null,null,5,...{5,5,5,...

次の例:{...,22,null,null,null,98,...}になる必要があります: {...,22,60,60,60,98,...}; 3 つの値はすべて、および( )nullの平均値に置き換えられます。2298(22+98)/2

最後の例:{...,23,null}になる必要が{...,23,23}あります。配列の最後の要素であるため、 にnull置き換えられます。23

この問題のアルゴリズムを作成する方法を知っている人はいますか?

4

4 に答える 4

3

これが で行われると仮定するとArrayList<Integer>:

//iterate over all values
for (int i=0; i<array.size(); i++) {
    //get the value at the current position
    Integer value= array.get(i);

    //if the value is null...
    if (value == null) {

        //find out the closes left and right values
        Integer leftValue= goLeft(array, i);
        Integer rightValue= goRight(array, i);

        //if both are integer values, find middle
        if (leftValue != null && rightValue != null) {
            array.add(i, (leftValue + rightValue)/2);

        //if left one is integer, and the other one is null? end of the array
        } else if (leftValue != null && rightValue == null) {
            array.add(i, leftValue);

        //if the right one is integer, and the left one is null? begin of the array
        } else if (leftValue == null && rightValue != null) {
            array.add(i, rightValue);

        //well, if everything is null, just add zeros
        } else {
            array.add(i, 0);
        }
    }
}

あなたに残されているのは、実装することです

  • goLeft(ArrayList<Integer> array, int index)
  • goRight(ArrayList<Integer> array, int index).

前後関係や名前を見ただけで、彼らはかなり単純明快だと思います。

于 2013-06-12T14:15:43.040 に答える
0

これが私の見解です:

public static void fill(Integer[] newarr, Integer[] arr, int index) {
    if (arr[index] != null) {
        newarr[index] = arr[index];
        return;
    }

    Integer a = null, b = null;

    int i = index;
    while (i < arr.length - 1 && (a = arr[++i]) == null);

    i = index;
    while (i > 1 && (b = arr[--i]) == null);

    newarr[index] = (a == null) ? b : (b == null) ? a : (a + b) / 2;
}

それで:

Integer[] arr = { null, null, 5, 111, 21, null, 22, null, null, null,
        98, 25, 47, null, 1, 23, null };

Integer[] newarr = new Integer[arr.length];

for (int i = 0; i < arr.length; i++)
    fill(newarr, arr, i);

System.out.println(Arrays.toString(newarr));
[5、5、5、111、21、21、22、60、60、60、98、25、47、24、1、23、23]
于 2013-06-12T14:29:55.863 に答える
0
  1. null のすべてのシーケンスを決定します (各シーケンスの開始インデックスと終了インデックスを格納します)
  2. 各シーケンスの境界要素を決定し、平均を計算します (余分なケースの開始と配列の終了を正しく処理するようにしてください)
  3. null を計算値で置き換えます
于 2013-06-12T14:10:24.520 に答える