hulu笔试

 

1417. 称重问题
将金币尽量分成均匀三堆。如果正好平分就正常操作,余一个就是(3k,3k)上秤,但是最坏的情况是要找的金币在3k+1里,余两个就是(3k+1,3k+1)上秤,最坏的情况还是在3k+1里。

class Solution {
public:
    int minimumtimes(int n) {
        // Write your code here
        if (n<=1) return 0;
        int res=0;
        while (n>1) {
            int tmp=n%3;
            n=(n/3) + (tmp==0?0:1);
            res+=1;
        } 
        return res;
    }
};

1003. 二叉树剪枝
类似后序遍历,先处理左右子树,如果有全0的直接设置成NULL,不需要从根节点向下多次判断,也不用特意返回其他flag。

class Solution {
public:
    TreeNode * has_one(TreeNode * root) {
        if (root==NULL) return NULL;
        root->left=has_one(root->left);
        root->right=has_one(root->right);
        if (root->left==NULL && root->right==NULL && root->val==0) return NULL;
        else return root;
        
    }
    TreeNode * pruneTree(TreeNode * root) {
        // Write your code here
        if (root==NULL) return NULL;
        return has_one(root);
    }
};

1559. 取数求和
注意有可能溢出,还要在每一个可能超过1000000007的地方取余。

class Solution {
public:
    int takeTheElementAndQueryTheSum(vector &arr) {
        // Write your code here
        if (arr.size()<=1) return -1;
        long long res=0;
        long prefix=arr[0];
        for (int i=1;i

997. 打印组织结构图 

class people {
public:
    string ups;
    string title;
    string year;
    vector downs;
    //自定义构造函数必须记得同时定义默认无参构造函数
    people(){
        ups="";
        title="";
        year="";
        vector tmp;
        downs=tmp;
    }
    people(string _ups, string _title, string _year, vector _downs):
    ups(_ups),title(_title),year(_year),downs(_downs) {}
};
class Solution {
public:
    void DFShelper(string p, int level, vector &res, map &nodes) {
        string tmp="";
        for (int k=0;k getOrganization(vector> &relationship) {
        // Write your code here
        map nodes;
        string leader="";
        //先创建节点
        for (int i=0;i tmp;
            people p=people(relationship[i][1],relationship[i][2],relationship[i][3],tmp);
            nodes[relationship[i][0]]=p;
            //找到根节点
            if (relationship[i][1]=="NULL") leader=relationship[i][0];
        }
        //
        for (int i=0;i res;
        int level=0;
        //看题目要用深搜
        DFShelper(leader,level,res,nodes);
        return res;
    }
};

996. 最大斜率直线
如果暴力求解会超时。可以考虑,如果所有点按x轴坐标大小排序,最大斜率的点一定是相邻的两个点。假设对于x,y,z三个点,如果xz的斜率大于xy的斜率,那么yz斜率一定大于xz斜率。所以先排序就好。

struct point_index {
    int index;
    Point p;
};
bool cmp(point_index a, point_index b) {
    return a.p.x getPoints(vector &points) {
        // Write your code here
        vector res;
        if (points.size()==2) {res.push_back(0); res.push_back(1); return res;}
        vector ps;
        for (int i=0;imax_angle) {
                max_angle=angle;
                index1=ps[i].index;
                index2=ps[i+1].index;
            }
        }
        if (index1>index2) swap(index1,index2);
        res.push_back(index1);
        res.push_back(index2);
        return res;
    }
};

 

你可能感兴趣的:(LeetCode)