C++算法記錄

記錄部分算法

typedef float ElemType;
typedef struct node{
    ElemType data;
    struct node* lchild;
    struct node* rchild;
    struct node* parent;
}BTNode;
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
        val(x), next(nullptr) {
    }
};
/**向二叉樹中插入結點**/
void TreeNode::InsertIntoBitTree(BTNode **root,ElemType data)
{
    /*創建新結點保存待插入的data*/
    BTNode *newNode=static_cast<BTNode*>(malloc(sizeof(BTNode)));
    newNode->data=data;
    newNode->lchild=nullptr;
    newNode->rchild=nullptr;
    //考慮到 當輸入是空樹時 需要改變根結點(BiTNode *root)的值,所以這裏要求輸入根節點的地址(BiTNode **root類型)
    if(*root==nullptr)//說明是空樹
        {
            *root=newNode;//將新結點的指針newNode賦值給根結點的指針
            (*root)->parent=nullptr;
            (*root)->lchild=nullptr;
            (*root)->rchild=nullptr;
        }
    else if((*root)->lchild==nullptr)
    {
        /*左子樹爲空 則將新結點newNode的指針賦值給左子樹結點的指針*/
        (*root)->lchild=newNode;
        (*root)->lchild->parent=*root;//左子樹的父節點爲根結點

    }

    else if((*root)->rchild==nullptr)
    {
        /*右子樹爲空 則將新結點newNode的指針賦值給右子樹結點的指針*/
        (*root)->rchild=newNode;
        (*root)->rchild->parent=*root;//右子樹的父節點爲根結點
    }

    /*如果根節點、左右子樹都不爲空 遞歸向左子樹插入data*/
    /*這樣構造的樹的特點是:根結點的右子樹只有一個結點*/
    else if(static_cast<int>(data) == 8 || static_cast<int>(data) == 6)
        InsertIntoBitTree(&((*root)->rchild),data);
    else
        InsertIntoBitTree(&((*root)->lchild),data);
}
/*中序遍歷並輸出:左 根結點 右*/
void TreeNode::MidPrint(BTNode *root)
{
    if(root==nullptr)
    {
        printf("invalid MidPrint");
        exit(-1);
    }
    if(root->lchild!=nullptr)
    MidPrint(root->lchild);
    qDebug() << root->data << "\n";
    if(root->rchild!=nullptr)
    MidPrint(root->rchild);
}

//中序遍歷
void TreeNode::InOrderWithoutRecursion1(BTNode* root)
{
    //空樹
    if (root == nullptr)
        return;
    //樹非空
    BTNode* p = root;
    QStack<BTNode*> s;
    while (!s.empty() || p)
    {
        //一直遍歷到左子樹最下邊,邊遍歷邊保存根節點到棧中
        while (p)
        {
            s.push(p);
            p = p->lchild;
        }
        //當p爲空時,說明已經到達左子樹最下邊,這時需要出棧了
        if (!s.empty())
        {
            p = s.top();
            s.pop();
            qDebug() << p->data;
            //進入右子樹,開始新的一輪左子樹遍歷(這是遞歸的自我實現)
            p = p->rchild;
        }
    }
}
//後序遍歷
void TreeNode::InOrderWithoutRecursion2(BTNode* root)
{
    //空樹
    if (root == nullptr)
        return;
    //樹非空
    BTNode* p = root,*pre = nullptr;
    QStack<BTNode*> s;
    s.push_back(p);
    
    while (!s.empty()){
        p = s.top();
        
        if(((p->lchild ==nullptr) && (p->rchild ==nullptr))  ||
                ((pre == p->lchild || pre == p->rchild) && pre != nullptr) ){
             
            qDebug() << p->data ;
            s.pop();
            pre = p;
        }
        else
        {
            if (p->rchild != nullptr)
                s.push(p->rchild);
            if (p->lchild != nullptr)
                s.push(p->lchild);
        }
    }
    
}
int TreeNode::treeDepth(BTNode *root)
{
    if(root == nullptr)
        return 0;
    int lnum = treeDepth(root->lchild);
    int rnum = treeDepth(root->rchild);
    return std::max(lnum,rnum) + 1;

}
//找到環鏈表的入口
ListNode *TreeNode::EntryNodeOfLoop(ListNode *pHead)
{
    ListNode *fast = pHead;
    ListNode *slow = pHead;
    while (fast && fast->next) {
        fast = fast->next->next;
        slow = slow->next;
        if(fast == slow) break;
    }
    if(!fast || !fast->next) return nullptr;
    fast = pHead;
    while (fast != slow) {
        fast = fast->next;
        slow = slow->next;
    }
    return fast;
}

    //單個字符出現位置
    int FirstNotRepeatingChar(std::string str);
    //最長相同字符
    QString maxlen(QString qstr1,QString qstr2);
    //循環左移
    std::string LeftRotateString(std::string str, int n);
    //數組中兩個只出現一次的數
    void FindNumsAppearOnce(QVector<int> data,int* num1,int *num2);
    //奇偶分離(奇靠前)
    void reOrderArray(QVector<int> &array);
    //可走1階和2階,走n階有幾種走法
    int stepsNum(int nstep);
    //空格替換
    void replaceSpace(char *str,int length);
    bool Find(int target, QVector<QVector<int> > array);



int algorithmString::FirstNotRepeatingChar(std::string str){
    QMap<char,int> mp;
    for (const char ch : str) {
        mp.insert(ch,mp[ch]+1);
        //++mp[ch];
    }
    for (int i=0; i< str.length(); ++i) {
        if (mp[str[i]] == 1) return i;
    }
    return -1;
//    int num = 0;
//    int len = str.length();
//    if(len==0) return -1;
//    if(len==1) return 0;
//    bool flag[len];
//    for(int i=len-1;i>=0;i--){
//        for(int j=i+1;j<len;j++){
//            if(str[i]==str[j]){
//                flag[i] = true;
//                flag[j] = true;
//                break;
//            }
//            num++;
//        }
//    }
//    qDebug() << "num--"<<num;
//    for(int i=0;i<len;i++){
//        if(flag[i]==false)
//            return i;
//    }
//    return -1;
}
//求最大相同字符串
QString algorithmString::maxlen(QString qstr1,QString qstr2){
    QVector<QVector<int>> record(qstr1.length(),QVector<int>(qstr2.length()));
    int maxLen=0,maxEnd=0;
    for (int i=0; i<qstr1.length();i++) {
        for (int j=0; j<qstr2.length();j++) {
            if(qstr1[i] == qstr2[j]){
                if(i==0 || j==0){
                    record[i][j] = 1;
                }else {
                    record[i][j] = record[i-1][j-1] + 1;
                }
            }
            else {
                record[i][j] = 0;
            }
            if(record[i][j] > maxLen){
                maxLen = record[i][j];
                maxEnd = i;
            }
        }
    }
    return qstr1.mid(maxEnd - maxLen + 1, maxLen);
}

std::string algorithmString::LeftRotateString(std::string str, int n)
{
    if(n>str.length())return "";
    std::string rstr = "";
    for (int i=0;i<str.length()-n;i++) {
        rstr += str[n+i];
    }
    for (int i=n;i>0;i--) {
        rstr += str[n-i];
    }
    return rstr;
}
void algorithmString::FindNumsAppearOnce(QVector<int> data,int* num1,int *num2) {
    int m_num1=0,m_num2=0;
    QMap<int,int> num;
    for (int i=0;i<data.count();i++) {
        ++num[data[i]];
    }
    for (int i=0;i<data.count();i++) {
        if(num[data[i]] == 1 && m_num1 == 0)
            m_num1 = data[i];
        if(num[data[i]] == 1 && m_num1 != 0)
            m_num2 = data[i];
    }
    *num1 = m_num1;
    *num2 = m_num2;
}
void algorithmString::reOrderArray(QVector<int> &array) {
//    QVector<int> arr;
//    for (const int v : array) {
//        if (v&1) arr.push_back(v); // 奇數
//    }
//    for (const int v : array) {
//        if (!(v&1)) arr.push_back(v); // 偶數
//    }
//    std::copy(arr.begin(), arr.end(), array.begin());
    int Temp;
    int j=0;
    for (int i=0;i<array.size();i++) {
        if(array[i] & 1){
            if(i != j){
                Temp = array[i];
                for (int k=i;k>j;k--) {
                    array[k] = array[k-1];
                }
                array[j] = Temp;
                j++;
            }else {
                j++;
            }
        }
    }
}
int algorithmString::stepsNum(int nstep){
    if(nstep == 1)
        return 1;
    else if(nstep == 2)
        return 2;
    else if(nstep == 3)
        return 3;
    else {
        return stepsNum(nstep-1) + stepsNum(nstep - 2);
    }


    //時間複雜度O(n),空間複雜度O(n)
//    QVector<int> dp( nstep + 1, 0);
//        dp[1] = 1;
//        for (int i=2; i<=nstep; ++i) {
//            dp[i] = dp[i-1] + dp[i-2];
//        }
//        return dp[nstep];

}

void algorithmString::replaceSpace(char *str, int length)
{
    if(str == nullptr || length == 0) return;
    int cnt = 0;
    for (int i=0;i<length;i++) {
        if(str[i] == ' ') cnt++;
    }
    if(cnt == 0) return;

    int cntLength = length + cnt*2;
    for (int i=length;i>=0;i--) {
        if(str[i] == ' '){
            str[cntLength--] = '0';
            str[cntLength--] = '2';
            str[cntLength--] = '%';
        }
        else {
            str[cntLength--] = str[i];
        }
    }
}

bool algorithmString::Find(int target, QVector<QVector<int> > array)
{
 if (array.size() ==0 || array[0].size() ==0) return false;
     for (const auto& vec : array) {
         for (const int val : vec) {
             if (val == target)
                 return true;
         }
     }
     return false;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章