头条笔试题

来源:互联网 发布:房价m2知乎 编辑:程序博客网 时间:2024/05/17 02:38

第一题:二维平面最外围的点
这里写图片描述
思路:对于任何一个点(xj,yj)来说,其右上方的点(x,y)必然是 x>xj且y>yj;
将所有点按纵坐标递减排序。遍历一遍,遍历过程中,对于某个点Pi(xi,yi),先于此点遍历的点一定纵坐标大于yi,后于此点遍历的纵坐标一定小于等于yi。那么只需要记录前i个点中横坐标的最大值max,就可以知道存不存在点满足x>xi了。如果max大于xi,那么Pi一定不满足条件,反之,Pi是满足条件的点。

#include <iostream>#include <fstream>#include <vector>#include <algorithm>using namespace std;struct point {    int x;    int y;    void print() {        cout << x << "," << y << endl;    }};bool sort_by_Y(point p1, point p2) {    if(p1.y != p2.y) return p1.y > p2.y;    else return p1.x > p2.x;}bool sort_by_X(point p1, point p2) {    if(p1.x != p2.x) return p1.x < p2.x;    else return p1.y < p2.y;}int main() {    int N;    cin >> N;    point *p = new point[N];    int i;    for (i = 0; i < N; i++) {        cin >> p[i].x >> p[i].y;    }    sort(p, p + N, sort_by_Y);    vector<point> res;    int max = 0;    for (i = 0; i < N; i++) {        if (max < p[i].x) {            max = p[i].x;            res.push_back(p[i]);        }    }    sort(res.begin(), res.end(), sort_by_X);//结果按x从到大排序    for (i = 0;i < res.size();i++) {        cout << res[i].x << " " << res[i].y << endl;    }    //system("pause");    return 0;}       
原创粉丝点击