所以说我有一个像这样的2D数组:
[1, 2, 3]
[1, 2, 3, 3]
[2, 3, 1]
如果出现此问题,我的函数将返回true,因为忽略了顺序和重复项。如果我改为输入这样的2D数组:
[1, 2, 3]
[2, 3, 4]
[6, 7, 1, 2]
它将返回false,因为没有数组具有相同的数字等。
无论如何,我试图编写一个可以找到这些等效数组的程序。目前,我有这样的事情:
public static boolean checkEqual(Integer[][] array){
//get number of rows
int numRows = array[0].length;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numRows; i++){
boolean alreadySeen = false;
for (int j = 0; j < array[i].length; j++){
if (map.containsKey(array[i][j])){
//Do not add duplicates in the same row to the map
if (!alreadySeen){
int count = map.get(array[i][j]);
count++;
map.put(array[i][j], count);
alreadySeen = true;
}
}
else{
map.put(array[i][j], 1);
}
}
}
boolean overall = false;
for (Map.Entry<Integer, Integer> entry : map.entrySet()){
if (entry.getValue() == numRows){
overall = true;
}
else{
return false;
}
}
return overall;
}
然而,这总是返回False,我觉得由于所有的循环和检查,这是一个非常低效的方法。有人会碰巧有任何关于如何以更有效的方式做到这一点的提示吗?谢谢!
答案 0 :(得分:1)
如果我理解正确,你可以使用这样的东西:
import java.util.Set;
import java.util.HashSet;
public class Equaller
{
public static boolean checkEqual(Integer[][] array) {
Set<Integer> firstSet = new HashSet<Integer>();
Set<Integer> secondSet = new HashSet<Integer>();
if (array.length > 0) {
// Fill first set
final Integer[] firstArray = array[0];
for (int i=0; i < firstArray.length; ++i) {
firstSet.add(firstArray[i]);
}
// Compare 2D array with first set
for (int i=1; i < array.length; ++i) {
final Integer[] intArray = array[i];
for (int j=0; j < intArray.length; ++j) {
if (!firstSet.contains(intArray[j])) {
return false;
}
}
}
// Create second set
if (array.length > 1) {
final Integer[] secondArray = array[1];
for (int i=0; i < secondArray.length; ++i) {
secondSet.add(secondArray[i]);
}
// Compare first array
if (firstSet.size() != secondSet.size()) {
return false;
}
}
return true;
}
return false;
}
public static void main(String[] argv) {
Integer[][] aa = new Integer[][] {
{1,2,3},
{1,2,3,3},
{2,3,1}};
System.out.println(checkEqual(aa));
Integer[][] ab = new Integer[][] {
{1,2,3},
{2,3,4},
{6,7,1,2}};
System.out.println(checkEqual(ab));
}
}
它会返回
true
false
答案 1 :(得分:1)
清理了xio4的解决方案:
import java.util.Set;
import java.util.HashSet;
public class Equaller {
public static boolean checkEqual(Integer[][] array) {
if (array.length > 0) {
Set<Integer> firstSet = new HashSet<Integer>(array[0].length);
// fill first set
for (Integer i : array[0]) {
firstSet.add(i);
}
// compare 2D array with first set
for (Integer[] intArray : array) {
Set<Integer> secondSet = new HashSet<Integer>(firstSet.size());
for (Integer i : intArray) {
if (!firstSet.contains(i)) {
return false;
}
secondSet.add(i);
}
if (firstSet.size() != secondSet.size()) {
return false;
}
}
}
return true;
}
}