Skip to content

Commit a19e7c7

Browse files
add Java solution for 2001
1 parent 078a2ca commit a19e7c7

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

src/main/java/com/fishercoder/solutions/_2001.java

+22
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,26 @@ public long interchangeableRectangles(int[][] rectangles) {
2222
return answer;
2323
}
2424
}
25+
26+
public static class Solution2 {
27+
/**
28+
* credit: https://leetcode.com/problems/number-of-pairs-of-interchangeable-rectangles/discuss/1458404/Java-or-HashMap
29+
* <p>
30+
* This is an even smarter way to solve this problem:
31+
* whenever we encounter a rectangle that has the samw ratio we met before, just increment the answer by the count of this ratio
32+
* because this new rectangle could be matched up with all previously encountered ones!
33+
* <p>
34+
* This is 100% beat on all submissions on space and time as of 9/12/2021.
35+
*/
36+
public long interchangeableRectangles(int[][] rectangles) {
37+
Map<Double, Integer> map = new HashMap<>();
38+
long ans = 0l;
39+
for (int[] rec : rectangles) {
40+
double ratio = (double) rec[0] / rec[1];
41+
ans += map.getOrDefault(ratio, 0);
42+
map.put(ratio, map.getOrDefault(ratio, 0) + 1);
43+
}
44+
return ans;
45+
}
46+
}
2547
}

src/test/java/com/fishercoder/_2001Test.java

+3
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,17 @@
99

1010
public class _2001Test {
1111
private static _2001.Solution1 solution1;
12+
private static _2001.Solution2 solution2;
1213

1314
@BeforeClass
1415
public static void setup() {
1516
solution1 = new _2001.Solution1();
17+
solution2 = new _2001.Solution2();
1618
}
1719

1820
@Test
1921
public void test1() {
2022
assertEquals(6, solution1.interchangeableRectangles(CommonUtils.convertLeetCodeIrregularLengths2DArrayInputIntoJavaArray("[4,8],[3,6],[10,20],[15,30]")));
23+
assertEquals(6, solution2.interchangeableRectangles(CommonUtils.convertLeetCodeIrregularLengths2DArrayInputIntoJavaArray("[4,8],[3,6],[10,20],[15,30]")));
2124
}
2225
}

0 commit comments

Comments
 (0)