3

Javaで次のことを行うための解決策を見つけようとしています。

int [] keys = new int[]{7,9,4,2,8,5,6,0}; // not necessarily a continuous series
double [] vals = new double[]{10,31,20,22,21,30,33,34}; // same length as keys<br/>

keys(低いものから高いものへ)を並べ替え、対応するvalsものをその順序で並べる必要があります。たとえば、この場合の出力は次のようになります。

sorted keys:   0,  2,  4,  5,  6,  7,  8,  9
ordered vals: 34, 22, 20, 33, 10, 30, 21, 31

keys[i]またはのようなインデックスを与えるキーと値にアクセスする必要がある一部の計算では、マップを使用できませんvals[j]

前もって感謝します、

4

7 に答える 7

0

これは私がそれを行った方法であり、動作します:

  1. というキーと値のペア ホルダー クラスを作成しますimplements Comparable
  2. キーと値のペアのクラスをリストに追加し、それを使用Collections.sort()して並べ替えます。

例:

キーと値のペア クラス:

/**
 * @author Buhake Sindi
 * @since 28 August 2013
 *
 */
public class Pair implements Comparable<Pair> {

    private int key;
    private double value;

    /**
     * @param key
     * @param value
     */
    public Pair(int key, double value) {
        super();
        this.key = key;
        this.value = value;
    }

    /**
     * @return the key
     */
    public int getKey() {
        return key;
    }

    /**
     * @return the value
     */
    public double getValue() {
        return value;
    }

    /* (non-Javadoc)
     * @see java.lang.Comparable#compareTo(java.lang.Object)
     */
    public int compareTo(Pair o) {
        // TODO Auto-generated method stub
        if (getKey() > o.getKey()) {
            return 1;
        }

        if (getKey() < o.getKey()) {
            return -1;
        }

        return 0;
    }
}

テストケース:

/**
 * @author Buhake Sindi
 * @since 28 August 2013
 *
 */
public class PairComparer {

    public static void main(String[] args) {
        List<Pair> pairs = new ArrayList<Pair>(Arrays.asList(new Pair(7, 10d),
                                         new Pair(9, 31d),
                                         new Pair(4, 20d),
                                         new Pair(2, 22d),
                                         new Pair(8, 21d),
                                         new Pair(5, 30d),
                                         new Pair(6, 33d),
                                         new Pair(0, 34d)));
        Collections.sort(pairs);
        for (Pair pair : pairs) {
            System.out.println(pair.getKey() + " - " + pair.getValue());
        }
    }
}

出力:

0 - 34.0
2 - 22.0
4 - 20.0
5 - 30.0
6 - 33.0
7 - 10.0
8 - 21.0
9 - 31.0

お役に立てれば。

于 2013-08-28T15:56:06.370 に答える
0

最も簡単な方法は、最初にキーと値のペアを に入れ、TreeMap次にそのマップのエントリを反復処理して、Map.Entry各キー ペアを書き直すことです。擬似コード:

sortedMap = new TreeMap

for i between 0 and keys.length
    sortedMap.put(keys[i], vals[i])

i = 0
for entry in sortedMap:
    keys[i] = entry.getKey()
    vals[i] = entry.getValue()
    ++i
于 2013-08-28T15:40:25.680 に答える