LintCode 820. 矩形

给出一个set,问能不能找到四个点组成平行于坐标轴的矩形,如果能输出YES,否则输出NO。

注意事项
set的点数小于2000,坐标范围在[-10000000,10000000]。

样例
给出 set = [[0,0],[0,1],[1,1],[1,0]],返回 YES。

解释:
set中的四个点能组成平行于坐标轴的矩形。
给出 set = [[0,0],[0,1],[1,1],[2,0]],返回 NO。

解释:
set中的四个点不能组成平行于坐标轴的矩形。

 

思路:和在点集中找到一条直线所能经过的最多的点有异曲同工之妙,可以先把所有点放到一个unordered_set的字典里面用于查找(可以自己设计hash函数,我把点转换成了字符串,算是一个取巧的写法,不过牺牲了一定的速度),然后任选两点,可以确定这两点如果组成矩阵则另两点的坐标(A.x,B.y)和(B.x,A.y)也就能够得到,检查字典是否存在就行了。
时间复杂度O(n^2),空间复杂度O(n)

 

 1 // class Point {
 2 // public:
 3 //     int x, y;
 4 //     Point(int x, int y) {
 5 //         this->x = x;
 6 //         this->y = y;
 7 //     }
 8 // };
 9 
10 
11 class Solution {
12 public:
13     /**
14      * @param pointSet: The point set
15      * @return: The answer
16      */
17     string rectangle(vector<Point> &pointSet) {
18         // Write your code here
19         int size = pointSet.size();
20         string yes = "YES";
21         string no = "NO";
22         if(size<4) return no;
23         unordered_set<string> dict;//字典
24         for(auto p:pointSet){
25             string temp = point2string(p.x,p.y);
26             dict.insert(temp);
27         }
28         for(int i=0;i<size;++i){
29             for(int j=0;j<size;++j){
30                 if(i==j || i<j) continue;//去重处理
31                 if(pointSet[i].x == pointSet[j].x || pointSet[i].y == pointSet[j].y) continue;//若两个点x或者y相同,则这种坐标查找会出问题,跳过
32                 if(dict.count(point2string(pointSet[i].x,pointSet[j].y))&&dict.count(point2string(pointSet[j].x,pointSet[i].y))) return yes;//判断另外两个点是否在dict里
33             }
34         }
35         return no;
36     }
37     
38     string point2string(int x,int y){ //点坐标转换成string,unordered_set对于string有默认hash函数
39         string temp = "";
40         temp += to_string(x);
41         temp += "#";
42         temp += to_string(y);
43         return temp;
44     }
45 };

 

posted @ 2018-04-14 09:44  J1ac  阅读(158)  评论(0编辑  收藏  举报