是长方形的Java吗?哈希图

webghufk  于 2022-10-01  发布在  Java
关注(0)|答案(2)|浏览(128)

给定长度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;
jdzmm42g

jdzmm42g1#

Does this help you

private static int rectangleCanBeBuild(int a, int b, int c, int d) {
    HashMap<Integer, Integer> hm = new HashMap<>();
    hm.put(a, hm.getOrDefault(a, 0) + 1);
    hm.put(b, hm.getOrDefault(b, 0) + 1);
    hm.put(c, hm.getOrDefault(c, 0) + 1);
    hm.put(d, hm.getOrDefault(d, 0) + 1);
    int count = 0;
    for (int key : hm.keySet()) {
       //use xor to find if there are 2 sides with same length
        count ^= hm.get(key);

        }
    return count == 0 ? 1 : 0;
}

Return 0 for your Input. Return 1 for

int a = 2;
int b = 3;
int c = 2;
int d = 3;
yi0zb3m4

yi0zb3m42#

You can generate a HashMap of frequencies for each size and then check if all its values equal to 2 (because there are two distinct sizes of rectangle's sides).

That how it might be implemented using Stream API and collectortoMap():

public static int canFormRectangle(int... args) {
    return Arrays.stream(args)
        .boxed()
        .collect(Collectors.toMap(
            Function.identity(),
            i -> 1,
            Integer::sum
        ))
        .values().stream()
        .allMatch(count -> count == 2)
        ? 1 : 0;
}

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].

public static int canFormRectangle(int... args) {

    Map<Integer, Integer> countBySide = new HashMap<>();

    for (int next: args) countBySide.merge(next, 1, Integer::sum);

    return new ArrayList<>(countBySide.values()).equals(List.of(2, 2)) ? 1 : 0;
}

相关问题