λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

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

 

λ°˜μ‘ν˜•