Skip to content

Commit

Permalink
feat: Update Solution.java
Browse files Browse the repository at this point in the history
  • Loading branch information
CodersAcademy006 authored Aug 13, 2024
1 parent cd6eed5 commit abf0f7c
Showing 1 changed file with 29 additions and 43 deletions.
72 changes: 29 additions & 43 deletions solution/0300-0399/0391.Perfect Rectangle/Solution.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
class Solution {
import java.util.HashMap;
import java.util.Map;

public class Solution {
public boolean isRectangleCover(int[][] rectangles) {
long area = 0;
int area = 0;
int minX = rectangles[0][0], minY = rectangles[0][1];
int maxX = rectangles[0][2], maxY = rectangles[0][3];
Map<Pair, Integer> cnt = new HashMap<>();
Map<String, Integer> cnt = new HashMap<>();

for (int[] r : rectangles) {
area += (r[2] - r[0]) * (r[3] - r[1]);
Expand All @@ -13,52 +16,35 @@ public boolean isRectangleCover(int[][] rectangles) {
maxX = Math.max(maxX, r[2]);
maxY = Math.max(maxY, r[3]);

cnt.merge(new Pair(r[0], r[1]), 1, Integer::sum);
cnt.merge(new Pair(r[0], r[3]), 1, Integer::sum);
cnt.merge(new Pair(r[2], r[3]), 1, Integer::sum);
cnt.merge(new Pair(r[2], r[1]), 1, Integer::sum);
String[] points = {
r[0] + "," + r[1],
r[0] + "," + r[3],
r[2] + "," + r[3],
r[2] + "," + r[1]
};

for (String point : points) {
cnt.put(point, cnt.getOrDefault(point, 0) + 1);
}
}

if (area != (long) (maxX - minX) * (maxY - minY)
|| cnt.getOrDefault(new Pair(minX, minY), 0) != 1
|| cnt.getOrDefault(new Pair(minX, maxY), 0) != 1
|| cnt.getOrDefault(new Pair(maxX, maxY), 0) != 1
|| cnt.getOrDefault(new Pair(maxX, minY), 0) != 1) {
if (area != (maxX - minX) * (maxY - minY)
|| cnt.getOrDefault(minX + "," + minY, 0) != 1
|| cnt.getOrDefault(minX + "," + maxY, 0) != 1
|| cnt.getOrDefault(maxX + "," + maxY, 0) != 1
|| cnt.getOrDefault(maxX + "," + minY, 0) != 1) {
return false;
}

cnt.remove(new Pair(minX, minY));
cnt.remove(new Pair(minX, maxY));
cnt.remove(new Pair(maxX, maxY));
cnt.remove(new Pair(maxX, minY));

return cnt.values().stream().allMatch(c -> c == 2 || c == 4);
}

private static class Pair {
final int first;
final int second;
cnt.remove(minX + "," + minY);
cnt.remove(minX + "," + maxY);
cnt.remove(maxX + "," + maxY);
cnt.remove(maxX + "," + minY);

Pair(int first, int second) {
this.first = first;
this.second = second;
for (int c : cnt.values()) {
if (c != 2 && c != 4) return false;
}

@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair pair = (Pair) o;
return first == pair.first && second == pair.second;
}

@Override
public int hashCode() {
return Objects.hash(first, second);
}
return true;
}
}
}

0 comments on commit abf0f7c

Please sign in to comment.