创新工场笔试题

1.树的子结构问题,参照《剑指offer》上面试题18.

bool DoseTree1HaveTree2(BinaryTreeNode *pRoot1, BinaryTreeNode *pRoot2)
{
    if(pRoot2 == NULL)
        return true;
    if(pRoot1 == NULL)
        return false;
    if(pRoot1->m_nValue != pRoot2->m_nValue)
        return false;
    return DoseTree1HaveTree2(pRoot1->m_pLeft, pRoot2->m_pLeft) && DoseTree1HaveTree2(pRoot1->m_pRight, pRoot2->m_pRight);
}

bool HasSubTree(BinaryTreeNode *pRoot1, BinaryTreeNode *pRoot2)
{
    bool result = false;
    if(pRoot1 != NULL && pRoot1 != NULL)
    {
        result = DoesTree1HaveTree2(pRoot1, pRoot2);
        if(!result)
            result = HasSubTree(pRoot1->m_pLeft, pRoot2);
        if(!result)
            result = HasSubTree(pRoot1->m_pRight, pRoot2);
    }
    return result;
}

2.翻转字符串;

void reverse(string s)
{
    int n = s.size();
    int i = 0, j = n-1;
    while(i <= j)
    {
        swap(s[i], s[j]);
        i++;
        j--;
    }
}

3.加油站问题,参见leetcode题目Gas Station

int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
    int n=gas.size();
    if(n==0)
        return -1;
    int sum=0;
    int dif=0;
    int result=0;
    for(int i=0;i<n;i++)
    {
        sum+=gas[i]-cost[i];
        dif+=gas[i]-cost[i];
        if(sum<0)
        {
            result=(i+1)%n;
            sum=0;
        }
    }
    if(dif<0)
        return -1;
    return result;
}

 

posted @ 2014-09-24 21:23  Awy  阅读(284)  评论(0编辑  收藏  举报