这是一个问题: 有N个男孩和N个女孩。只有一个男孩和一个女孩可以形成一对舞蹈(即不允许同性别的舞蹈对)。制作配对的唯一其他条件是它们的高度绝对差应小于或等于K.
找出可以形成的最大对数,以便每个人都有一个独特的合作伙伴。
我想改进算法以减少时间.. 首先看代码:
//k is the maximum difference between pairs
int k = 5;
ArrayList<Integer> ArrBoys = new ArrayList<>(Arrays.asList(new Integer[]{28, 16, 22}));
ArrayList<Integer> ArrGirls = new ArrayList<>(Arrays.asList(new Integer[]{13, 10, 14}));
//sorting all arrays
Collections.sort(ArrBoys);
Collections.sort(ArrGirls);
System.out.println("After Sorting");
//printing arrays after sorting
for (Integer ArrBoy : ArrBoys) {
System.out.print(ArrBoy + " ");
}
System.out.println("");
for (Integer ArrGirl : ArrGirls) {
System.out.print(ArrGirl + " ");
}
System.out.println("");
//algorithm used to find the number of pairs
int count = 0;
for (Iterator<Integer> iteB = ArrBoys.iterator(); iteB.hasNext();) {
Integer ArrBoy = iteB.next();
for (Iterator<Integer> iteG = ArrGirls.iterator(); iteG.hasNext();) {
{
Integer ArrGirl = iteG.next();
int dif = (int) Math.abs(ArrBoy - ArrGirl);
if (dif <= k) {
System.out.println("we took " + ArrBoy + " from boys with "
+ ArrGirl + " from girls, thier dif < " + k);
ArrBoys.remove(ArrBoy);
ArrGirls.remove(ArrGirl);
iteB = ArrBoys.iterator();
count++;
break;
} else {
System.out.println("we try " + ArrBoy + " from boys with " + ArrGirl + " from grils but thier dif > " + (int) k);
//ArrGirls.remove(ArrGirl);
}
}
}
}
System.out.println("the number of pairs we can take is "+count);
此代码的输出为:
正如你看到这个算法效率低下,因为我们不需要开始比较第一个女孩对第二个男孩的身高,我们应该去找那个我们成对的前一个女孩之后的女孩。
例如: 在22高度的男孩,算法必须开始比较男孩的身高与14高的女孩,因为我们已经对它们进行排序,如果第一个男孩(较短)不能与第一个女孩成对,所以绝对是第二个男孩(更长)也不能,如果我们比较第一个女孩,我们就浪费时间。
我们可以通过两个选择来解决这个问题,或者通过在上一个男孩被停止之后让迭代器从女孩开始(我不知道如何用迭代器做),或者从arraylist一旦它不满足条件并让循环从第一个女孩开始(我试过这个,但它给了我一个例外)
如果可以,请通过以下两种方式解决......
答案 0 :(得分:1)
您必须添加更多条件。在这里,有三个选项:
以下是代码:
int count = 0;
int gLimit = 0;
for (int b = 0; b<ArrBoys.size();b++) {
if(gLimit == ArrGirls.size()) {
System.out.println("no more girl for boy " + ArrBoys.get(b));
}
for (int g = gLimit; g<ArrGirls.size();g++) {
{
int dif = ArrBoys.get(b) - ArrGirls.get(g);
if (Math.abs(dif) <= k) {
System.out.println("we took " + ArrBoys.get(b) + " from boys with "
+ ArrGirls.get(g) + " from girls, thier dif < " + k);
gLimit++;
count++;
break;
} else if (dif > k) {
System.out.println("we try " + ArrBoys.get(b) + " from boys with " + ArrGirls.get(g) + " from grils but thier dif > " + (int) k + ", girl too small, excluded");
gLimit++;
} else if (dif < -k) {
System.out.println("we try " + ArrBoys.get(b) + " from boys with " + ArrGirls.get(g) + " from grils but thier dif > " + (int) k + ", boy too small, excluded");
break;
}
}
}
}
我使用get index来提高列表内容的可靠性
这是ouput
After Sorting
16 22 28
10 13 14
we try 16 from boys with 10 from grils but thier dif > 5, girl too small, excluded
we took 16 from boys with 13 from girls, thier dif < 5
we try 22 from boys with 14 from grils but thier dif > 5, girl too small, excluded
no more girl for boy 28
the number of pairs we can take is 1