LIKE CODING: MJ [40] Count squares
Given a set of points, find all squares composed by four points of the set.
给你一些平面的点(坐标是整数),求能够成正方形的数目。
我想了想这题大概可以这么做:把每两个点之间的距离用hashmap存下来,key是
distance, values是arraylist of point pairs, 比如(p1, p2), (p3,p4)之间距离
都是6, 把他们都放到map.get(6)的list里面。这样一共要查(n,2)pairs, time也就是
(n^2). 下一步对于每一个distance, 查看对应的list size是不是大于4(至少有4个
pairs之间距离相同)。然后对于每一个list再进一步确定有没有正方形,比如
(p1,p2), (p1,p3), (p1,p4), (p2, p3), (p2, p4), (p3, p4) 都在list里,就可以确
认这四个点可以组成正方形。。。。确认的时候可以再建一个hashmap, map p1 to (p2
, p3, p4), p2 to (p3, p4), 然后找需要的pair是不是都在map里。。。就是好麻烦这
个solution, 不知有没有简单点的解法?
https://github.com/ashish1294/BugFreeCodes/blob/master/Code%20Chef/Count%20the%20squares.c
Read full article from LIKE CODING: MJ [40] Count squares
Given a set of points, find all squares composed by four points of the set.
给你一些平面的点(坐标是整数),求能够成正方形的数目。
我想了想这题大概可以这么做:把每两个点之间的距离用hashmap存下来,key是
distance, values是arraylist of point pairs, 比如(p1, p2), (p3,p4)之间距离
都是6, 把他们都放到map.get(6)的list里面。这样一共要查(n,2)pairs, time也就是
(n^2). 下一步对于每一个distance, 查看对应的list size是不是大于4(至少有4个
pairs之间距离相同)。然后对于每一个list再进一步确定有没有正方形,比如
(p1,p2), (p1,p3), (p1,p4), (p2, p3), (p2, p4), (p3, p4) 都在list里,就可以确
认这四个点可以组成正方形。。。。确认的时候可以再建一个hashmap, map p1 to (p2
, p3, p4), p2 to (p3, p4), 然后找需要的pair是不是都在map里。。。就是好麻烦这
个solution, 不知有没有简单点的解法?
https://github.com/ashish1294/BugFreeCodes/blob/master/Code%20Chef/Count%20the%20squares.c
vector<vector<pair<int, int>>> findSquares(vector<pair<int, int>> &points){
vector<vector<pair<int, int>>> ret;
unordered_set<string> ss;
//squares set
unordered_set<string> ps;
//points set
for
(auto p:points){
string key = to_string(p.first)+
" "
+to_string(p.second);
ps.insert(key);
}
int n = points.size();
for
(int i=0; i<n; ++i){
int x1 = points[i].first, y1 = points[i].second;
for
(int j=i+1; j<n; ++j){
int x2 = points[j].first, y2 = points[j].second;
int x3 = (x1+x2+y2-y1), y3 = (y1+y2+x1-x2);
int x4 = (x1+x2+y1-y2), y4 = (y1+y2+x2-x1);
if
(x3%2 || y3%2 || x4%2 || y4%2){
continue
;}
x3/=2; y3/=2; x4/=2; y4/=2;
string key3 = to_string(x3)+
" "
+to_string(y3);
string key4 = to_string(x4)+
" "
+to_string(y4);
if
(ps.find(key3)!=ps.end() && ps.find(key4)!=ps.end()){
vector<pair<int, int>> sq;
sq.push_back(points[i]);
sq.push_back(points[j]);
sq.push_back(pair<int, int>(x3, y3));
sq.push_back(pair<int, int>(x4, y4));
sort(sq.begin(), sq.end());
string key;
for
(auto p:sq)
key += to_string(p.first)+
" "
+to_string(p.second)+
" "
;
if
(ss.count(key)==0){
ret.push_back(sq);
ss.insert(key);
}
}
}
}
return
ret;
}