๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

IN DEPTH CAKE/Supercoder

[c++/LeetCode-Hash Table] 939. Minimum Area Rectangle

 

 

 

 

๋‚œ์ด๋„Medium

ํ‚ค์›Œ๋“œ: Hash Table

 

 

 

๐ŸŽฒ ๋ฌธ์ œ

X-Y ํ‰๋ฉด์ƒ์˜ ์ ๋“ค์˜ ๋ฐฐ์—ด points๊ฐ€ ์ฃผ์–ด์กŒ์Šต๋‹ˆ๋‹ค. ์—ฌ๊ธฐ์„œ points[i] = [xi, yi]์ž…๋‹ˆ๋‹ค.
์ด๋Ÿฌํ•œ ์ ๋“ค๋กœ ํ˜•์„ฑ๋œ X์ถ•๊ณผ Y์ถ•์— ํ‰ํ–‰ํ•œ ์ง์‚ฌ๊ฐํ˜•์˜ ์ตœ์†Œ ๋ฉด์ ์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. ๋งŒ์•ฝ ๊ทธ๋Ÿฌํ•œ ์ง์‚ฌ๊ฐํ˜•์ด ์—†๋‹ค๋ฉด, 0์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

 

๋ฌธ์ œ ์›๋ฌธ: https://leetcode.com/problems/minimum-area-rectangle/description/

 

Example 1:

Input: points = [[1,1],[1,3],[3,1],[3,3],[2,2]]
Output: 4

 

๐ŸŽฒ  ๋ฌธ์ œ ํ’€์ด

๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์‚ฌ๊ฐํ˜•์„ ํƒ์ƒ‰ํ•˜๋ฉด์„œ ์‚ฌ๊ฐํ˜•๋“ค ์ค‘ ์ตœ์†Œ ๋ฉด์  ๊ฐ’์„ ๊ตฌํ•˜๊ณ ์žํ•œ๋‹ค.

์ด๋ฅผ ์œ„ํ•ด์„œ ๋‘ ๊ฐœ์˜ ์ ์ด ์ฃผ์–ด์กŒ์„ ๋•Œ ์ด ๋‘ ์  ์™ธ์— ์‚ฌ๊ฐํ˜•์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์ ๋“ค์ด ์กด์žฌํ•˜๋Š” ์ง€ O(1) ์œผ๋กœ ํƒ์ƒ‰ํ•˜๋Š” ํ˜•ํƒœ๋กœ ์‚ฌ๊ฐํ˜• ๋ฉด์ ์„ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

 

class Solution {
public:
    int minAreaRect(vector<vector<int>>& points) {

        unordered_map<int, set<int>> hash;
        for(auto point : points){
            auto x = point[0], y = point[1];
            hash[x].insert(y);
        }

        int MAX = 16 * pow(10, 8);
        int ans = MAX;

        for(auto i=0; i < points.size()-1; ++i){
            for(auto j=i; j < points.size(); ++j){
                auto x1 = points[i][0], y1 = points[i][1];
                auto x2 = points[j][0], y2 = points[j][1];

                if(x1 == x2) continue;
                if(y1 == y2) continue;

                // check rectangle
                if(hash[x1].find(y2) != hash[x1].end() && hash[x2].find(y1) != hash[x2].end())
                    ans = min(ans, abs(x1-x2) * abs(y1-y2));
            }
        }

        if(ans == MAX)
            ans = 0;

        return ans;
        
    }
};

 

 

ํ•ด๋‹น ์ฑ„๋„์—์„œ Leet Code ํ•ด์„คํ•ด ๋†“์€ ๊ฒƒ๋“ค์ด ์žˆ๋Š”๋ฐ ๊ณผ์ •์ด ์ฒด๊ณ„์ ์ด๊ณ  ์ข‹์€ ๊ฒƒ ๊ฐ™๋‹ค :)  

https://youtu.be/xvuuENPhEH4?feature=shared

 

๋ฐ˜์‘ํ˜•