創新工場筆試題

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.翻轉字符串;ui

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 Stationspa

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;
}
相關文章
相關標籤/搜索