Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commita19e7c7

Browse files
add Java solution for 2001
1 parent078a2ca commita19e7c7

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,26 @@ public long interchangeableRectangles(int[][] rectangles) {
2222
returnanswer;
2323
}
2424
}
25+
26+
publicstaticclassSolution2 {
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+
publiclonginterchangeableRectangles(int[][]rectangles) {
37+
Map<Double,Integer>map =newHashMap<>();
38+
longans =0l;
39+
for (int[]rec :rectangles) {
40+
doubleratio = (double)rec[0] /rec[1];
41+
ans +=map.getOrDefault(ratio,0);
42+
map.put(ratio,map.getOrDefault(ratio,0) +1);
43+
}
44+
returnans;
45+
}
46+
}
2547
}

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,17 @@
99

1010
publicclass_2001Test {
1111
privatestatic_2001.Solution1solution1;
12+
privatestatic_2001.Solution2solution2;
1213

1314
@BeforeClass
1415
publicstaticvoidsetup() {
1516
solution1 =new_2001.Solution1();
17+
solution2 =new_2001.Solution2();
1618
}
1719

1820
@Test
1921
publicvoidtest1() {
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)

[8]ページ先頭

©2009-2025 Movatter.jp