[593. Valid Square] C++


  • 0
    class Solution {
    public:
    bool check(vector<int>& p1, vector<int>& p2, vector<int>& p3){
        if(p1 == p2 || p2 == p3 || p1 == p3) return false;
        int x1 = p2[0] - p1[0];
        int y1 = p2[1] - p1[1];
        int x2 = p3[0] - p2[0];
        int y2 = p3[1] - p2[1];
        return (x1*x2 + y1*y2 == 0) && (x1*x1 + y1*y1 == x2*x2 + y2*y2);
    }
    bool validSquare(vector<int>& p1, vector<int>& p2, vector<int>& p3, vector<int>& p4) {
        if(p1.empty() || p2.empty() || p3.empty() || p4.empty()) return false;
        vector<vector<int> > points = {p1,p2,p3,p4};
        int x = p1[0], y = p1[1], index = 0;
        for(int i = 1; i < 4; ++i){
            if(points[i][0] < x || (points[i][0] == x && points[i][1] < y)){
                x = points[i][0];
                y = points[i][1];
                index = i;
            }
        }
        swap(points[0], points[index]);
        sort(points.begin()+1, points.end(), [](vector<int> a, vector<int> b){
            return a[1] < b[1] || (a[1] == b[1] && a[0] > b[0]);
        });
        for(int i = 0; i < 4; ++i){
            if(!check(points[i%4], points[(i+1)%4], points[(i+2)%4])){
                return false;
            }
        }
        return true;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.