平分的直线 牛客网 程序员面试金典 C++ Python
-
题目描述
-
在二维平面上,有两个正方形,请找出一条直线,能够将这两个正方形对半分。假定正方形的上下两条边与x轴平行。
-
给定两个vecotrA和B,分别为两个正方形的四个顶点。请返回一个vector,代表所求的平分直线的斜率和截距,保证斜率存在。
-
测试样例:
-
[(0,0),(0,1),(1,1),(1,0)],[(1,0),(1,1),(2,0),(2,1)]
-
返回:[0.0,0.5]
C++
/*
struct Point {
int x;
int y;
Point() :
x(0), y(0) {
}
Point(int xx, int yy) {
x = xx;
y = yy;
}
};*/
class Bipartition {
public:
//run:5ms memory:476k
vector<double> getBipartition(vector<Point> A, vector<Point> B) {
double centerax = (A[0].x+A[1].x+A[2].x+A[3].x)/4.0;
double centeray = (A[0].y+A[1].y+A[2].y+A[3].y)/4.0;
double centerbx = (B[0].x+B[1].x+B[2].x+B[3].x)/4.0;
double centerby = (B[0].y+B[1].y+B[2].y+B[3].y)/4.0;
vector<double> ret;
ret.push_back((centeray-centerby)/(centerax-centerbx));
ret.push_back(centeray- ret[0] * centerax);
return ret;
}
};
Python
# class Point:
# def __init__(self, a=0, b=0):
# self.x = a
# self.y = b
class Bipartition:
def getBipartition(self, A, B):
centerax = (A[0].x+A[1].x+A[2].x+A[3].x)/4.0
centeray = (A[0].y+A[1].y+A[2].y+A[3].y)/4.0
centerbx = (B[0].x+B[1].x+B[2].x+B[3].x)/4.0
centerby = (B[0].y+B[1].y+B[2].y+B[3].y)/4.0
ret = []
ret.append((centeray-centerby)/(centerax-centerbx))
ret.append(centeray- ret[0] * centerax)
return ret;