首页 > 9.18 心动网络编程两道(CPP)
头像
南七技校
发布于 2021-09-18 18:22
+ 关注

9.18 心动网络编程两道(CPP)

1.给四个点,不分顺序,求是否为矩形(100%)
/**
 * struct Point {
 *	int x;
 *	int y;
 *	Point(int xx, int yy) : x(xx), y(yy) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 返回N个0或1,1表示对应的那组数据是矩形
     * @param N int整型 
     * @param points Point类vector<vector<>> 第一层vector必定N个元素,里面的每个vector必定是4个Point
     * @return int整型vector
     */
    vector<int> rectangle(int N, vector<vector<Point> >& points) {
        // write code here
        vector<int> ret;
        for (int i = 0; i < N; i++) {
            //中点重合大法
            double sumX = 0, sumY = 0;
            for (int j = 0; j < 4; j++) {
                sumX += points[i][j].x;
                sumY += points[i][j].y;
            }
            sumX /= 2;
            sumY /= 2;
            bool flag = false;
            if (sumX == points[i][0].x + points[i][1].x && sumY == points[i][0].y + points[i][1].y) {
                //排除菱形
                double x1 = points[i][2].x - points[i][0].x;
                double x2 = points[i][2].x - points[i][1].x;
                double y1 = points[i][2].y - points[i][0].y;
                double y2 = points[i][2].y - points[i][1].y;
                if (x1*x2 + y1*y2 == 0) flag = true;
            }
            if (sumX == points[i][0].x + points[i][2].x && sumY == points[i][1].y + points[i][3].y) {
                //排除菱形
                double x1 = points[i][1].x - points[i][0].x;
                double x2 = points[i][1].x - points[i][2].x;
                double y1 = points[i][1].y - points[i][0].y;
                double y2 = points[i][1].y - points[i][2].y;
                if (x1*x2 + y1*y2 == 0) flag = true;
            }
            if (sumX == points[i][0].x + points[i][3].x && sumY == points[i][1].y + points[i][2].y) {
                //排除菱形
                double x1 = points[i][1].x - points[i][0].x;
                double x2 = points[i][1].x - points[i][3].x;
                double y1 = points[i][1].y - points[i][0].y;
                double y2 = points[i][1].y - points[i][3].y;
                if (x1*x2 + y1*y2 == 0) flag = true;
            }
            if (flag) ret.push_back(1);
            else ret.push_back(0);
        }
        return ret;
    }
};


全部评论

(4) 回帖
加载中...
话题 回帖