diff --git a/leetcode/DIRECTORY.md b/leetcode/DIRECTORY.md index 091453f8..1e3ffc23 100644 --- a/leetcode/DIRECTORY.md +++ b/leetcode/DIRECTORY.md @@ -56,6 +56,7 @@ | 206 | [Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/) | [C](./src/206.c) | Easy | | 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array/) | [C](./src/215.c) | Medium | | 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate/) | [C](./src/217.c) | Easy | +| 223 | [Rectangle Area](https://leetcode.com/problems/rectangle-area/) | [C](./src/223.c) | Medium | | 226 | [Invert Binary Tree](https://leetcode.com/problems/invert-binary-tree/) | [C](./src/226.c) | Easy | | 231 | [Power of Two](https://leetcode.com/problems/power-of-two/) | [C](./src/231.c) | Easy | | 234 | [Palindrome Linked List](https://leetcode.com/problems/palindrome-linked-list/) | [C](./src/234.c) | Easy | diff --git a/leetcode/src/223.c b/leetcode/src/223.c new file mode 100644 index 00000000..6f424dc9 --- /dev/null +++ b/leetcode/src/223.c @@ -0,0 +1,24 @@ +#define min(X, Y) ((X) < (Y) ? (X) : (Y)) + +int intersectionSize(int p11, int p12, int p21, int p22){ + if (p11 >= p22 || p12 <= p21){ + return 0; + } + + if (p11 < p21){ + return min(p12 - p21, p22 - p21); + } + + return min(p22 - p11, p12 - p11); +} + +// Calculation area of the A, then area of the B then minus intersection of A and B +// Runtime: O(1) +// Space: O(1) +int computeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2){ + int areaA = (ay2 - ay1) * (ax2 - ax1); + int areaB = (by2 - by1) * (bx2 - bx1); + int areaInteresection = intersectionSize(ax1, ax2, bx1, bx2) * intersectionSize(ay1, ay2, by1, by2); + + return areaA + areaB - areaInteresection; +}