2 回答
TA贡献1815条经验 获得超10个赞
您已将内环放在外面,将外环放在里面!
里面说:
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
...
所以为了让你的代码工作,你只需要以相反的顺序传递参数:
int[] transformed = pair.transform(arrayTwo, arrayOne);
或者,我建议这样做,切换循环:
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条经验 获得超21个赞
如果您可以创建对象并使用更多内存,那么下一步很容易:
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);
}
}
创建一个代表每一对的类并实现 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;
}
添加回答
举报