我有一个5个骰子的数组,我正在尝试检查它是否有两个不同的对。可以说我有(1、2、2、3)或(3、3、4、4、5)我希望它返回true。我该怎么办?
让第一个骰子成为int [] firstDice = new int [] {1,1,2,2,3};
让第二个骰子为int [] secondDice = new int [] {3,3,4,4,5};
要检查每对是否不同,只需同时遍历两个对象(前提是骰子的数量相同)。这是方法的示例:
private boolean checkDifferentDice(int [] firstDice, int [] secondDice){
boolean result = true;
for (int i = 0; i < firstDice.length; i++)
{
if (firstDice[i] == secondDice[i])
return false;
}
return result;
}
很简单。考虑您有一个数组,arr [5] = {1,1,2,2,3};您可以使用Set解决此问题。我正在通过使用count变量来跟踪这对货币对。
1,1,2,2,3->我要一个一个地迭代数组。当我第一次得到1时,我将其放置。第二次,检查集合,如果它包含,那么它必须是一对。
public bool findSet(int[] arr)
{
HashSet<Integer> set = new HashSet<>();
int count = 0;
for(int n : arr)
{
if(set.contains(n))
count++;
else
set.add(n);
}
return count == 2;
}