每天幾道編程題

1.在一個二維數組中,每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。

/*
這個二維數組是有序的從左向右看遞增,從上到下遞增
從左下角開始查詢,比他大的右移,比它小的上移
*/
class Solution {
public:
    bool Find(int target, vector<vector<int> > array) 
    {
        int row = array.size();   //行數
        int col = array.size();   //列數
        //從左下角開始尋找
        int i = 0;
        int j = 0;
        for( i = row - 1,j =0;i >= 0 && j < col;)
        {
            if( target == array[i][j])
            {
                return true;
            }
            if( target < array[i][j])
            {
                i --;
            }
            if( target > array[i][j])
            {
                j ++;
            }
        }
        return false;
    }
};

2.請實現一個函數,將一個字符串中的空格替換成“%20”。例如,當字符串爲We Are Happy.則經過替換之後的字符串爲We%20Are%20Happy。

class Solution {
public:
    void replaceSpace(char *str, int length) {
        if (str ==NULL || length <= 0)
            return;
        int origi_len = 0;
        int spacenum = 0;
        for (int i = 0; str[i] != '\0'; i++)
        {
            origi_len++;
            if (str[i] == ' ')
                spacenum++;
        }
        int new_len = origi_len + spacenum * 2;
        int p = origi_len;
        int q = new_len;
        while (q >= 0)
        {
            if (str[p] == ' ')
            {
                str[q--] = '0';
                str[q--] = '2';
                str[q--] = '%';
            }
            else
                str[q--] = str[p];
            p--;
        }
    }
};

3.輸入一個鏈表,從尾到頭打印鏈表每個節點的值。
(1)

//插入數據到鏈表
struct ListNode
{
    int value;
    ListNode *next;
};

void AddToTail(ListNode **head,int val)
{
    ListNode *temp = new ListNode();
    temp->next = NULL;
    temp->value = val;
    if( *head == NULL)
    {
        *head = temp;
    }
    else
    {
        ListNode *node = *head;
        while( node->next != NULL)
        {
            node = node->next;
        }
        node->next = temp;
    }
}
//從尾到頭打印鏈表
void Print(ListNode *head)
{
    if( head == NULL)
    {
        return ;
    }
    stack<ListNode *> stack;
    ListNode *node = head;
    while( node != NULL)
    {
        stack.push(node);
        node = node->next;
    }
    while( !stack.empty())
    {
        node = stack.top();
        cout<<node->value<<" ";
        stack.pop();
    }
}

(2)

class Solution {
public:
    vector<int> printListFromTailToHead(struct ListNode* head) {
//利用棧的逆序輸出特性        
        stack<int> stack;
        vector<int> vector;
        struct ListNode *p = head;
        if (head != NULL) {
            stack.push(p->val);
            while((p=p->next) != NULL) {
                stack.push(p->val);
            }
            while(!stack.empty()) {
                vector.push_back(stack.top());
                stack.pop();
            }
        }
        return vector;
    }

};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章