2 回答

TA貢獻1815條經(jīng)驗 獲得超10個贊
您已將內(nèi)環(huán)放在外面,將外環(huán)放在里面!
里面說:
For each pair x in array one
For each pair y in array two
If x and y are equal
...
你做了:
For each pair x in array two
For each pair y in array one
If x and y are equal
...
所以為了讓你的代碼工作,你只需要以相反的順序傳遞參數(shù):
int[] transformed = pair.transform(arrayTwo, arrayOne);
或者,我建議這樣做,切換循環(huán):
private int[] transform(int[][] dictionary, int[][] lookup) {
int[] result = new int[dictionary.length];
for (int dictionaryIndex = 0; dictionaryIndex < dictionary.length; dictionaryIndex++) {
int[] dictionaryPair = dictionary[dictionaryIndex];
int indexOf = -1;
for (int index = 0; index < lookup.length; index++) {
int[] pair = lookup[index];
if (dictionaryPair[0] == pair[0] && dictionaryPair[1] == pair[1]) {
indexOf = index;
break;
}
}
if (indexOf != -1) {
result[dictionaryIndex] = indexOf;
}
}
return result;
}

TA貢獻1842條經(jīng)驗 獲得超21個贊
如果您可以創(chuàng)建對象并使用更多內(nèi)存,那么下一步很容易:
public class Main {
static class Pair {
private int[] a;
Pair(int[] a) {
this.a = a;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Pair)) return false;
Pair pair = (Pair) o;
return Arrays.equals(a, pair.a);
}
@Override
public int hashCode() {
return Arrays.hashCode(a);
}
}
public static void main(String[] args) {
int[][] arrayOne = {{0, 1}, {1, 0}, {2, 1}, {2, 2}, {1, 1}, {1, 2}, {0, 0}, {2, 0}, {0, 2}};
int[][] arrayTwo = {{0, 0}, {0, 1}, {0, 2}, {1, 0}, {1, 1}, {1, 2}, {2, 0}, {2, 1}, {2, 2}};
List<Pair> lookup = Stream.of(arrayTwo).map(Pair::new).collect(Collectors.toList());
List<Pair> dictionary = Stream.of(arrayOne).map(Pair::new).collect(Collectors.toList());
List<Integer> result = dictionary.stream().map(lookup::indexOf).collect(Collectors.toList());
System.out.println(result);
}
}
創(chuàng)建一個代表每一對的類并實現(xiàn) equals 和 hashCode 方法,這樣我們就可以使用 indexOf 在查找集合中找到所需對的索引。
沒有額外的對象:
private int[] transform(int[][] dictionary, int[][] lookup) {
int[] result = new int[dictionary.length];
for (int i = 0; i < dictionary.length; i++) {
for (int j = 0; j < lookup.length; j++) {
if (lookup[j][0] == dictionary[i][0] && lookup[j][1] == dictionary[i][1]) {
result[i] = j;
break;
}
}
}
return result;
}
添加回答
舉報