给定长度a、b、c、d,找出是否可以形成矩形?如果是,则返回1,否则返回0。我正在使用Hashmap和XOR运算,我想知道我的问题解决过程中是否有什么问题。测试用例失败-a=2,b=3,c=2,d=2(不知道为什么?)
HashMap<Integer, Integer> hm = new HashMap<>();
int [] numbers = {A,B,C,D};
for(int i=0;i<numbers.length;i++)
{
hm.putIfAbsent(numbers[i],hm.getOrDefault(numbers[i],0)+1);
}
int res = 0;
for(int val : hm.values())
{
res = res ^ val;
}
if(hm.size() == 2 && res == 0)
{
return 1;
}
return 0;
2条答案
按热度按时间jdzmm42g1#
Does this help you
Return 0 for your Input. Return 1 for
yi0zb3m42#
You can generate a
HashMap
of frequencies for each size and then check if all its values equal to2
(because there are two distinct sizes of rectangle's sides).That how it might be implemented using Stream API and collector
toMap()
:The same using plain loops. We can dump all values (frequencies of each side) into a list and check if this list is equal to a list
[2,2]
.