剑指offer算法题

typedef struct listNode
{
    int val;
    struct listNode* next;
    struct listNode* randomNext;
}listNode;

#pragma mark 测试克隆
void test(listNode* head)
{
    std::stack<listNode*> stack;
    listNode* p = head;
    while(p)
    {
        NSLog(@"orinal :%@",@(p -> val));
        if (p -> randomNext) {
            NSLog(@"random:%@",@(p -> randomNext -> val));
        }
        stack.push(p);
        p = p ->next;
    }
    
    while (!stack.empty())
    {
//        listNode* p = stack.top();
//
//        NSLog(@"%@",@(p -> val));
//        stack.pop();
    }
}

//listNode* merge11(listNode* p1,listNode* p2)

#pragma mark 链表反转
listNode* reverse1(listNode* head){
    if (head == NULL || head -> next == NULL){
        return NULL;
    }
    
    listNode* p1 = head;
    listNode* p2 = head -> next;
    listNode* p3 = p2 -> next;
    
    p1 -> next = NULL;
    
    while (p3) {
        
        p2 -> next = p1;
        p1 = p2;
        p2 = p3;
        p3 = p3 -> next;
    }
    
    p2 -> next = p1;
    
    return p2;
}

#pragma mark 链表反转(递归实现)
listNode* recursive_reverse(listNode* head){
    
    if (head == NULL || head -> next == NULL){
        return head;
    }
    
    listNode* new_head = recursive_reverse(head -> next);
    
    listNode* p = head -> next;
    p -> next = head;
    head -> next = NULL;
    
    return new_head;
}

#pragma mark 汉诺塔

#pragma mark 克隆一个单链表
void testClone(listNode* head)
{
    if (head == NULL) {
        return;
    }
    
    listNode* node = head;
    
    while (node)
    {
        listNode* copyNode = (listNode*)malloc(sizeof(listNode));
        copyNode -> val = node -> val;
        copyNode -> next = node -> next;
        node -> next = copyNode;
        
        node = copyNode -> next;
    }
    
    node = head;
    
    while (node)
    {
        listNode* copyNode = node -> next;
        copyNode -> randomNext = node -> randomNext ? node -> randomNext -> next:NULL;
        node = copyNode -> next;
    }
    
    
    node = head;
    listNode* cloneHead = head -> next;
    while (node)
    {
        listNode* copyNode = node -> next;
        node -> next = copyNode ? copyNode -> next:NULL;
        node = copyNode;
    }
    
    test(cloneHead);
}

#pragma mark 链表中的环位置
listNode* meetNode(listNode* head){
    if (head == NULL) {
        return NULL;
    }
    
    listNode* pF = head -> next;
    listNode* pS = head;
    listNode* pMe = NULL;
    while (pF && pS)
    {
        if (pF == pS) {
            pMe = pF;
            break;
        }
        
        pS = pS -> next;
        pF = pF -> next;
        if (pF -> next) {
            pF = pF -> next;
        }
        
    }
    
    if (pMe == NULL) {
        return NULL;
    }
    
    listNode* pIter = pMe;
    int count = 1;
    while (pIter -> next != pMe) {
        pIter = pIter -> next;
        count++;
    }
    
    pF = head;
    pS = head;
    int index = 0;
    while (index++ < count){
        
        pF = pF -> next;
    }
    
    while (pF != pS) {
        pF = pF -> next;
        pS = pS -> next;
    }
    
    return pS;
    
}

#pragma mark 链表中第一次相遇的节点
listNode* firstMeetNode(listNode* head1,listNode* head2){
    
    if (head1 == NULL ) {
        return head2;
    }
    
    if (head2 == NULL) {
        return head1;
    }
    int h1c = length(head1);
    int h2c = length(head2);
    int diff = 0;
    listNode* pL = NULL;
    listNode* pS = NULL;
    if (h1c < h2c) {
        diff = h2c - h1c;
        pL = head2;
        pS = head1;
    }else{
        diff = h1c - h2c;
        pL = head1;
        pS = head2;
    }
    
    int index = 0;
    while (index++ < diff && pL) {
        pL = pL -> next;
    }
    while (pL && pS) {
        if (pL == pS) {
            return pL;
        }
        pL = pL -> next;
        pS = pS -> next;
    }
    
    return NULL;
}

#pragma mark 链表的长度
int length(listNode* node)
{
    if (node == NULL) {
        return 0;
    }
    listNode* p = node;
    
    int count = 0;
    while (p) {
        p = p -> next;
        count++;
    }
    
    return count;
}

#pragma mark 删除链表中重复的节点
listNode* deleteDuplicateNode(listNode* head){
    if (head == NULL) {
        return NULL;
    }
    
    listNode* pPre = NULL;
    listNode* pCur = head;
    listNode* pNext = NULL;
    
    while (pCur){
        pNext = pCur -> next;
        if ( pNext && pCur -> val == pNext -> val) {
            
            while (pNext -> next && pNext -> next -> val == pCur -> val) {
                pNext = pNext -> next;
            }
            
            if (pCur == head) {
                head = pNext -> next;
            }else{
                
                if (pPre) {
                    pPre -> next = pNext -> next;
                }
            }
            listNode* pNextBegin = pNext -> next;
            
            while (pCur && pCur != pNextBegin) {
                listNode* ptemp = pCur;
                pCur = pCur -> next;
                if(ptemp)free(ptemp);
            }
            
            pCur = pNextBegin;
        }else{
            
            pPre = pCur;
            pCur = pCur -> next;
        }
        
    }
    
    return head;
    
}


void listCreate()
{
    listNode* head = (listNode*)malloc(sizeof(listNode));
    head -> val = 1;
    head -> randomNext = NULL;
    
    listNode* p1 = (listNode*)malloc(sizeof(listNode));
    p1 -> val = 2;
    p1 -> randomNext = NULL;
    head -> next = p1;
    
    listNode* p2 = (listNode*)malloc(sizeof(listNode));
    p2 -> val = 2;
    p2 -> randomNext = head;
    p1 -> next = p2;
    
    listNode* p3 = (listNode*)malloc(sizeof(listNode));
    p3 -> val = 2;
    p2 -> next = p3;
    p3 -> randomNext = p1;
    
    listNode* p4 = (listNode*)malloc(sizeof(listNode));
    p4 -> val = 3;
    p3 -> next = p4;
    
    listNode* p5 = (listNode*)malloc(sizeof(listNode));
    p5 -> val = 2;
    p4 -> next = p5;
    
    p5 -> next = NULL;
    
    listNode* first = deleteDuplicateNode(head);
    test(first);
}

#pragma mark 依次删除环形链表第m个节点,求剩下最后一个节点(约瑟夫问题)
int delete_cylce_list_mth_node(int m){
    
    std::list<int> list;
    for (int i = 0; i < 5; i++) {
        list.push_back(i);
    }
    
    std::list<int>::iterator current = list.begin();
    
    while (list.size() > 1) {
        
        for (int i = 1; i < m; i++) {
            current++;
            if (current == list.end()) {
                current = list.begin();
            }
        }
        
        std::list<int>::iterator next = ++current;
        if (next == list.end()) {
            next = list.begin();
        }
        
        --current;
        list.erase(current);
        current = next;
    }
    
    return *current;
}

#pragma mark 水仙花数
#define f_3(a) (a) * (a) * (a)
void narcissistic_number(){
    
    for (int i = 100; i < 1000; i++) {
        
        int result = f_3(i / 100 % 10) + f_3(i / 10 % 10) + f_3(i % 10);
        if (i == result) {
            NSLog(@"narcissistic_number:%d",i);
        }
    }
}

#pragma mark 股票的最大利润(股票的买入和卖出),第i天股票卖出最大利润计算为函数diff(i) 时间复杂度O(n)
int stone_max_value(int* numbers,int len,int& min_buys,int& max_sells){
    
    if (!numbers || len <= 1) {
        return 0;
    }
    
    int min_value = numbers[0];
    int max_diff = 0;
    for (int i = 1; i < len; i++) {
        
        int diff = numbers[i] - min_value;
        
        if (diff > max_diff) {
            max_diff = diff;
            max_sells = numbers[i];
        }
        
        if (min_value > numbers[i]) {
            min_value = numbers[i];
            min_buys = min_value;
        }
    }
    
    return max_diff;
    /**
     int numbers[] = {9,11,8,5,8,7,12,16,14,29,0,45,10,6,55,23,9,100,203,3,99,102};
     int min_buys = 0;
     int max_sells = 0;
     int max_value = stone_max_value(numbers,sizeof(numbers) / sizeof(int),min_buys,max_sells);
     */
}


#pragma mark 股票的最大利润(股票的买入和卖出),蛮力法 从最后一个开始计算 时间复杂度O(n2)
int stone_max_value_violence(int* numbers,int len,int& min_buys,int& max_sells){
    
    if (!numbers || len <= 1) {
        return 0;
    }

    int max_diff = 0;
    for (int i = len - 1; i > 0; i--) {
        
        for (int j = 0; j < i; j++) {
            
            int diff = numbers[i] - numbers[j];
            if (diff > max_diff) {
                max_diff = diff;
                min_buys = numbers[j];
                max_sells = numbers[i];
            }
        }
    }
    
    return max_diff;
    
    /**
     int numbers[] = {9,11,8,5,8,7,12,16,14,29,0,45,10,6,55,23,9,100,203,3,99,102};
     int violence_min_buys = 0;
     int violence_max_sells = 0;
     int violence_max_value = stone_max_value_violence(numbers,sizeof(numbers) / sizeof(int),violence_min_buys,violence_max_sells
     */
}

bool equal(double num1,double num2){
    if ((num1 - num2) > -0.0000001 && (num1 - num2) < 0.0000001) {
        return true;
    }
    
    return false;
}

#pragma mark 浮点数 n次方
double test_power(double base,int exponent)
{
    if (equal(base, 0.0)) {
        return 0.0;
    }
    
    unsigned int absExponent = exponent > 0 ? (unsigned int)exponent : (unsigned int)-exponent;
    
    double result = 0.0;
    if (exponent == 0) {
        result = 1;
    }
    
    int count = 0;
    result = 1;
    while (count++ < absExponent) {
        result *= base;
    }
    
    if (exponent < 0) {
        result = 1.0 / result;
    }
    
    return result;
}

#pragma mark 顺时针打印矩阵
void printMatrix(std::vector<std::vector<int>> matrix)
{
    
    std::vector<int> result;
    int rows = (int)matrix.size();
    int cols = (int)matrix[0].size();
    if (cols == 0 && cols == 0) {
        return;
    }
    int left = 0;
    int top = 0;
    int right = cols - 1;
    int bottom = rows - 1;
    
    while (left < right && top < bottom) {
        
        for (int index = left; index <= right; index++) {
            result.push_back(matrix[top][index]);
        }
        
        for (int index = top + 1; index <= bottom; index++) {
            result.push_back(matrix[index][right]);
        }
        
        for (int index = right - 1; index >= left; index--) {
            result.push_back(matrix[bottom][index]);
        }
        
        for (int index = bottom - 1; index > top; index--) {
            result.push_back(matrix[index][left]);
        }
        
        
        left++;
        top++;
        right--;
        bottom--;
    }
    
    int bre = 10;
    /**
     //1 2 3 4 5
     //6 7 8 9 10
     //11 12 13 14 15
     //16 17 18 19 20
     std::vector<std::vector<int>> matrix;
     
     std::vector<int> vector;
     vector.push_back(1);
     vector.push_back(2);
     vector.push_back(3);
     vector.push_back(4);
     vector.push_back(5);
     matrix.push_back(vector);
     vector.clear();
     
     vector.push_back(6);
     vector.push_back(7);
     vector.push_back(8);
     vector.push_back(9);
     vector.push_back(10);
     matrix.push_back(vector);
     vector.clear();
     
     vector.push_back(11);
     vector.push_back(12);
     vector.push_back(13);
     vector.push_back(14);
     vector.push_back(15);
     matrix.push_back(vector);
     vector.clear();
     
     vector.push_back(16);
     vector.push_back(17);
     vector.push_back(18);
     vector.push_back(19);
     vector.push_back(20);
     matrix.push_back(vector);
     vector.clear();
     */
}


// 2 3 4 2 6 2 5 1
// 4 6 6 6 6
#pragma mark 滑动窗口
vector<int> slideWindow(vector<int> &sourceVec,int size)
{
    vector<int> retWindow;
    deque<int> indexs;
    for (int index = 0; index < size; index++) {
        
        while (!indexs.empty() && sourceVec[index] >= sourceVec[indexs.back()]) {
            indexs.pop_back();
        }
        indexs.push_back(index);
    }
    
    retWindow.push_back(sourceVec[indexs.front()]);
    
    for (int index = size; index < sourceVec.size(); index++) {
        
        while (!indexs.empty() && sourceVec[index] >= sourceVec[indexs.back()]) {
            indexs.pop_back();
        }
        
        if (!indexs.empty() && indexs.front() <= (index - size)) {
            indexs.pop_front();
        }
        
        indexs.push_back(index);
        
        retWindow.push_back(sourceVec[indexs.front()]);
    }
//    vector<int> vec;
//    vec.push_back(2);
//    vec.push_back(3);
//    vec.push_back(4);
//    vec.push_back(2);
//    vec.push_back(6);
//    vec.push_back(2);
//    vec.push_back(5);
//    vec.push_back(1);
//
//    vector<int> ret = slideWindow(vec, 3);
    
    return retWindow;
}
#include<functional>
#include <algorithm>
class Solution {
public:
    void Insert(int num)
    {
        // 如果已有数据为偶数,则放入最小堆
        if(((max.size() + min.size()) & 1) == 0){
            // 如果插入的数字小于最大堆里的最大的数,则将数字插入最大堆
            // 并将最大堆中的最大的数字插入到最小堆
            if(max.size() > 0 && num < max[0]){
                // 插入数据插入到最大堆数组
                max.push_back(num);
                // 调整最大堆
                push_heap(max.begin(), max.end(), less<int>());
                // 拿出最大堆中的最大数
                num = max[0];
                // 删除最大堆的栈顶元素
                pop_heap(max.begin(), max.end(), less<int>());
                max.pop_back();
            }
            // 将数据插入最小堆数组
            min.push_back(num);
            // 调整最小堆
            push_heap(min.begin(), min.end(), greater<int>());
        }
        // 已有数据为奇数,则放入最大堆
        else{
            if(min.size() > 0 && num > min[0]){
                // 将数据插入最小堆
                min.push_back(num);
                // 调整最小堆
                push_heap(min.begin(), min.end(), greater<int>());
                // 拿出最小堆的最小数
                num = min[0];
                // 删除最小堆的栈顶元素
                pop_heap(min.begin(), min.end(), greater<int>());
                min.pop_back();
            }
            // 将数据插入最大堆
            max.push_back(num);
            push_heap(max.begin(), max.end(), less<int>());
        }
    }
    
    double GetMedian()
    {
        // 统计数据大小
        int size = min.size() + max.size();
        if(size == 0){
            return 0;
        }
        // 如果数据为偶数
        if((size & 1) == 0){
            return (min[0] + max[0]) / 2.0;
        }
        // 奇数
        else{
            return min[0];
        }
    }
private:
    // 使用vector建立最大堆和最小堆,min是最小堆数组,max是最大堆数组
    vector<int> min;
    vector<int> max;
};

 
#import <pthread.h>
#pragma mark 将两个有序的数组合并为一个有序的数组
void mergeTwoArray(int* pPre,int len1,int* pAfter,int len2){
    int total_len = len1 + len2;
    int count = total_len;
    len2--;
    len1--;
      while (total_len-- != 0) {
        
       if(len2 >= 0 && len1 >= 0 && *(pAfter + len2) >= *(pPre + len1)) {
           *(pAfter + total_len) = *(pAfter + len2);
           len2--;
       }else{
           *(pAfter + total_len) = *(pPre + len1);
           len1--;
       }
    }
    
    while (count-- != 0) {
        NSLog(@"%@,count:%d",@(*(pAfter + count)),count);
    }
    
   
    int br4ek = 0;
}

#pragma mark 将一个数组前部分有序和后边部分有序合并
void mergeTwoPartition(int* vector,int len)
{
    int middle = (len - 1) >> 1;
    
    int high = len - 1;
    int low = middle;
    
    while (high >= middle) {
    
        while (vector[high] >= vector[low]) {
            high--;
        }
        
        int temp = vector[high];
        vector[high] = vector[low];
        vector[low] = temp;
        
        while (low >= 1 && vector[low] < vector[low - 1]) {
            
            int temp = vector[low];
            vector[low] = vector[low - 1];
            vector[low - 1] = temp;
            low--;
        }
        
        high--;
    }
}

#pragma mark 快速 排序
void quick_sort(int* vec,int low,int high){
    if (low >= high) {
        return;
    }
    
    int left = low;
    int right = high;
    int key = vec[low];
    while (low < high) {
        
        while (vec[high] >= key && low < high) {
            high--;
        }
        vec[low] = vec[high];
        
        while (vec[low] <= key && low < high) {
            low++;
        }
        
        vec[high] = vec[low];
    }
    
    vec[low] = key;
    quick_sort(vec,left,low - 1);
    quick_sort(vec,low + 1,right);
}

#pragma mark 直接插入排序
void directly_insert_sort(int* vec,int len){
    
    if (!vec || len <= 1) {
        return;
    }
    
    for (int i = 0; i < len; i++) {
        
        for (int j = 0; j < i; j++) {
            if (vec[i] < vec[j]) {
                int temp = vec[i];
                for (int k = i; k > j; k--) {
                    vec[k] = vec[k - 1];
                }
                vec[j] = temp;
            }
        }
    }
    /***
     int vec[] = {2,5,2,3,9,1,0,22,4,44,23,21,234,10};
     directly_insert_sort(vec, sizeof(vec)/sizeof(int));
     */
}

void binary_merge_sort()
{
    
}


struct TN
{
    int val;
    struct TN* l;
    struct TN* r;
    struct TN* parent;
    
    TN()
    {
        memset(this,0,sizeof(struct TN));
    }
};
    
#pragma mark 根据先序列,中序列,构建二叉树
TN* constructTN(int* preOrder,int* midOrder,int length){
    if (!preOrder || !midOrder || length <= 0) {
        return NULL;
    }
    
    struct TN* root = new struct TN();
    root -> val = *preOrder;
    
    int mid_index = 0;
    while (mid_index <= (length - 1) && *preOrder != *(midOrder + mid_index)) {
        mid_index++;
    }
    
    root -> l = constructTN(preOrder + 1,midOrder,mid_index);
    root -> r = constructTN((preOrder + mid_index + 1),midOrder + mid_index + 1,(length - mid_index - 1));
    
    
    return root;
    /***test
     int preOrder[] = {1,2,4,7,3,5,6,8};
     int midOrder[] = {4,7,2,1,5,3,8,6};
     TN* ret = constructTN(preOrder, midOrder, 8);
     printTNPreOrder(ret);
     */
}
    
    
#pragma mark  二叉最大高度等于 根节点到叶子节点路径的最大值
int binary_tree_max_depth(TN* head){
    
    if (!head) {
        return 0;
    }
    
    int left = binary_tree_max_depth(head -> l);
    int right = binary_tree_max_depth(head -> r);
    
    return left > right ? (left + 1):(right + 1);
    /*** TN* root = NULL;
     int vec[] = {10,8,12,7,9,11,13};
     
     create_TN_tree(root, vec, sizeof(vec) / sizeof(int), 0);
     int depth = binary_tree_max_depth(root);*/
    
}
    
#pragma mark 二叉搜索树的第k个结点 method1
TN* walk_k_node(TN* node,int& k){
    if (!node || k == 0 ) {
        return NULL;;
    }
    
    TN* target = NULL;
    
    if(node -> l){
        target = walk_k_node(node -> l,k);
    }
    
    NSLog(@"%d",node -> val);
    
    if (k == 1) {
        target = node;
    }
    k --;
    if (node -> r && target == NULL) {
        target = walk_k_node(node -> r, k);
    }
    
    return target;
    /****
     TN* root = NULL;
     int vec[][4] = {10,8,12,7,9,11,13};
     
     create_TN_tree(root, vec, sizeof(vec) / sizeof(int), 0);
     int k = 5;
     TN* target = walk_k_node(root, k);
     */
}

#pragma mark 二叉搜索树的第k个结点 method2
void kth_node(TN* node,TN* &target,int& k){
    
    if (!node || k == 0) {
        target = NULL;
        return;
    }
    
    kth_node_core(node, target, k);
}

void kth_node_core(TN* node,TN* &target,int& k){
   
    if(node -> l){
        kth_node_core(node -> l,target,k);
    }

    if(k == 1){
        target = node;
    }

    k--;
    
    if (node -> r) {
         kth_node_core(node -> r,target,k);
    }
    
 
    /****
     TN* root = NULL;
     int vec[] = {10,8,12,7,9,11,13};
     
     create_TN_tree(root, vec, sizeof(vec) / sizeof(int), 0);
     int k = 5;
     TN* target = NULL;
     target = walk_k_node(root, k);
     NSLog(@"method1:%d",target -> val);
     target = NULL;
     int b = 5;
     kth_node(root, target, b);
     NSLog(@"method2:%d",target -> val);
     int breakp = 0;
     */
}

#pragma mark 判断二叉树是否是个平衡二叉树(递归)
bool is_balance_binary_tree(TN* root){
    
    if (!root) {
        return true;
    }
    
    int left = binary_tree_max_depth(root -> l);
    int right = binary_tree_max_depth(root -> r);
    
    if (left - right > 1 || left - right < -1) {
        
        return false;
    }
    

    return is_balance_binary_tree(root -> l) && is_balance_binary_tree(root -> r);
    /**
     TN* root = NULL;
     int vec[] = {10,8,12,7,9,11,13};
     
     create_TN_tree(root, vec, sizeof(vec) / sizeof(int), 0);
     bool ret = is_balance_binary_tree(root);
     */
    
    //    TN* root = NULL;
    //    root = new TN();
    //    root -> val = 1;
    //    root -> l = new TN();
    //    root -> l -> val = 3;
    //    root -> l -> l = new TN();
    //    root -> l -> l -> val = 3;
}

#pragma mark 查找字符串中最长子字符串(动态规划算法,计算每一个索引结尾子字符串的最大子字符串)
int search_max_substr_len(char* str,int len,int& last_index){
    
    if (!str || len <= 0) {
        return -1;
    }
    
    int position[26];
    memset(position, -1, sizeof(position));
    int max_len = 0;
    int current_len = 0;
    for (int i = 0; i < len; i++) {
        
        int d = position[str[i] - 'a'];
        
        if ((d >= 0 && i - d > current_len) || d == -1) {
            current_len++;
        }else{
            current_len = i - d;
        }
        
        position[str[i] - 'a'] = i;
        
        if (current_len > max_len) {
            max_len = current_len;
            last_index = i;
        }
    }

    return max_len;
    /*
     0 1 2 3 4 5 6 7 8 9 10 11
     e a b c d a e c f g e g
    
    char* str = "eabcdaecfgeg";
    int last_index = 0;
    int len = search_max_substr_len(str, strlen(str),last_index);
     */
}

#pragma mark 礼物的最大价值 method1
int get_max_present_value(int chess_card[][4],int rows,int cols){
    
    if (!chess_card || rows <= 0 || cols <= 0 ) {
        return 0;
    }

    int** max_values = new int*[rows];
    for (int i = 0; i < rows; i++) {
        max_values[i] = new int[cols];
    }
    
    for (int i = 0; i < rows; i++) {
        
        for(int j = 0; j < cols;j++){
          
            int left = 0;
            int top = 0;
            
            if (i > 0) {
                top = max_values[i - 1][j];
            }
        
            if (j > 0) {
                left = max_values[i][j - 1];
            }
            
            max_values[i][j] = std::max(top, left) + chess_card[i][j];
        }
    }
    
    int max_value = max_values[rows - 1][cols - 1];
    
    for (int i = 0; i < rows; i++) {
        delete max_values[i];
    }
    
    delete [] max_values;
    
    return max_value;
    /*
     int chess_cards[][4] = {
         1,30,30,8,
         12,2,19,6,
         5,7,24,11,
         3,7,16,5
     };
     
     int max_value = get_max_present_value(chess_cards,4,4);
     */
}

#pragma mark 礼物最大价值 method2
int get_max_present_value_method_2(int chess_card[][4],int rows,int cols){
    
    if (!chess_card || rows <= 0 || cols <= 0 ) {
        return 0;
    }
    
    int* max_values = new int[cols];
    for (int i = 0; i < rows; i++) {
        
        for(int j = 0; j < cols;j++){
            
            int left = 0;
            int top = 0;
            
            if (i > 0) {
                top = max_values[j];
            }
            
            if (j > 0) {
                left = max_values[j - 1];
            }
            
            max_values[j] = std::max(top, left) + chess_card[i][j];
            NSLog(@"%d,max[j]:%d",chess_card[i][j],max_values[j]);
        }
    }
    
    int max_value = max_values[cols - 1];
    delete[] max_values;
    
    return max_value;
    /*
     int chess_cards[][4] = {
     
     1,30,30,8,
     12,2,19,6,
     5,7,24,11,
     3,7,16,5
     };
     
     int max_value2 = get_max_present_value_method_2(chess_cards,4,4);
     */
}

#pragma mark 礼物的最大价值,递归的计算
int get_max_present_value_method_recursive(int chess_card[][4],int rows,int cols){
    
    if (!chess_card || rows <= 0 || cols <= 0 ) {
        return 0;
    }
    
    return get_max_present_value_method_recursive_core(chess_card,rows,cols,0,0);
}

int get_max_present_value_method_recursive_core(int chess_card[][4],int rows,int cols,int i,int j){
    
    if (i >= rows || j >= cols) {
        
        return 0;
    }
    
    int right = chess_card[i][j] + get_max_present_value_method_recursive_core(chess_card,rows,cols,i,j + 1);
    
    int down = chess_card[i][j] + get_max_present_value_method_recursive_core(chess_card,rows,cols,i + 1,j);
   
    return right > down ? right : down;
    /*
     int chess_cards[][4] = {
     
     1,30,30,8,
     12,2,19,6,
     5,7,24,11,
     3,7,16,5
     };
     int max_value_recursive = get_max_present_value_method_recursive(chess_cards,4,4);
     */
}

#pragma mark 在字符串中第一次只出现一次的字符
char find_only_once_appear(char* str){
    
    if (!str) {
        return 0;
    }
    
    size_t len = strlen(str);
    
    int single_hash_table[256];
    for (int i = 0; i < 256; i++) {
        single_hash_table[i] = -1;
    }
    
    for (int i = 0; i < len; i++) {
        
        if (single_hash_table[str[i]] == -1) {
            single_hash_table[str[i]] = i;
        }else{
            single_hash_table[str[i]] = -2;
        }
    }
    
    char return_ch = 0;
    int min_index = 0x7FFFFFFF;
    for (int i = 0; i < 256; i++) {
        
        if (single_hash_table[i] >= 0 && single_hash_table[i] < min_index ) {
            
            min_index = single_hash_table[i];
            return_ch = (char)i;
        }
    }
    
    return return_ch;
}

#pragma mark 堆排序
void heap_adjust(int* vec,int start,int end){
    if (!vec || start < 0 || end < 0) {
        return;
    }
    
    int father = start;
    int son = 2 * father + 1;
    while (son <= end) {
        
        if (son + 1 <= end && vec[son] < vec[son + 1]) {
            son = son + 1;
        }
        
        if (vec[father] < vec[son]) {
            int temp = vec[father];
            vec[father] = vec[son];
            vec[son] = temp;
            
        }else{
            return;
        }
        
        father = son;
        son = 2 * father + 1;
        
    }
}


void heap_sort(int* vec,int len){
    if (!vec || len <= 0) {
        return;
    }
    
    for (int index = len / 2 - 1; index >= 0; index--) {
        heap_adjust(vec, index, len - 1);
    }
    
    for (int index = len - 1; index > 0; index--) {
        
        int temp = vec[0];
        vec[0] = vec[index];
        vec[index] = temp;
        
        heap_adjust(vec, 0, index - 1);
    }
}

    
#pragma mark 从上往下遍历二叉树,打印节点
void walk_tree(TN* head)
{
    if (!head) {
        return;
    }
    
    std::deque<TN*> queue;
    
    queue.push_back(head);
    while (!queue.empty()) {
        
        
        TN* node = queue.front();
        NSLog(@"%d",node -> val );
        if(node -> l){
            queue.push_back(node -> l);
        }
        if (node -> r) {
            queue.push_back(node -> r);
        }
        
        queue.pop_front();
    }
}
    
    
#pragma mark 从上往下遍历二叉树,并换行打印节点
void walk_tree_row(TN* head)
{
    if (!head) {
        return;
    }
    
    std::deque<TN*> queue;
    
    queue.push_back(head);
    int toBeDelete = 1;
    int nextLevelCount = 0;
    while (!queue.empty()) {
        
        TN* node = queue.front();
        printf("%d ",node -> val );
        if(node -> l){
            queue.push_back(node -> l);
            nextLevelCount++;
        }
        if (node -> r) {
            queue.push_back(node -> r);
            nextLevelCount++;
        }
        
        
        queue.pop_front();
        --toBeDelete;
        if (toBeDelete == 0) {
            printf("\n");
            toBeDelete = nextLevelCount;
            nextLevelCount = 0;
        }
    }
    /***
     
     int vec[] = {100,1,8,0,2,3,5,7,10,99,11,92,109};
     heap_sort(vec, sizeof(vec)/sizeof(int));
     TN* root = NULL;
     create_TN_tree(root, vec, sizeof(vec)/sizeof(int), 0);
     
     walk_tree_row(root);
     */
}

    
#pragma mark 二叉搜索树后序遍历 判断是不是后序遍历序列
bool last_walk_is_search_tree_order(int* vec,int len){
    
    if (!vec || len < 0) {
        return false;
    }
    
    if (len == 0) {
        return true;
    }
    
    int i = 0;
    for (; i < len - 1; i++) {
        if (vec[i] >= vec[len - 1]) {
            break;
        }
    }
    
    int j = i;
    for (; j < len - 1; j++) {
        if (vec[j] < vec[len - 1]) {
            return false;
        }
    }
    
    bool left = true;
    left = last_walk_is_search_tree_order(vec, i);
    
    bool right = true;
    right = last_walk_is_search_tree_order(vec + i + 1, len - 1 - i);
    
    return left && right;
    /***
     int vec[] = {7,4,6,5};
     int ret = last_walk_is_search_tree_order(vec, 4);
     */
}

#pragma mark 二叉树在某一路径的和为某一个值,并打印出路径

void print_binary_tree_sum(TN* head,int compareValue,vector<int> vec,int sumValue){
    
    if (!head) {
        return;
    }
    
    vec.push_back(head -> val);
    
    sumValue += head -> val;
    
    if (sumValue == compareValue) {
        for (std::vector<int>::iterator iter = vec.begin(); iter != vec.end(); iter++) {
            printf("%d ",*iter);
            
        }
        printf("\n");
    }
    
    
    print_binary_tree_sum(head -> l,compareValue,vec,sumValue);
    
    print_binary_tree_sum(head -> r,compareValue,vec,sumValue);
    
    sumValue -= vec.back();
    vec.pop_back();
    /***
     TN* root = NULL;
     int vec[] = {10,5,12,4,7};
     
     create_TN_tree(root, vec, sizeof(vec) / sizeof(int), 0);
     
     std::vector<int> emptyVec;
     print_binary_tree_sum(root, 19,emptyVec, 0);*/
    
}
    
void create_TN_tree(TN*& head,int* vec,int len,int index){
    
    if (!vec || len <= 0 || index < 0 || index >= len) {
        return;
    }
    
    head = new TN();
    head -> val = *(vec + index);
    head -> l = NULL;
    head -> r = NULL;
    head -> parent = NULL;
    
    create_TN_tree(head -> l, vec, len, 2 * index + 1);
    create_TN_tree(head -> r, vec, len, 2 * index + 2);
    
    if (head -> l) {
        head -> l -> parent = head;
    }
    
    if (head -> r) {
        head -> r -> parent = head;
    }

}

#pragma mark 先序遍历二叉树(非递归)
void previous_walk_tree_no_recursive(TN* head){
    
    std::stack<TN*> stack;
    if (head) {
        stack.push(head);
    }
    
    while (!stack.empty()) {
        
        TN* node = stack.top();
        NSLog(@"%s,%d",__func__,node -> val);
        stack.pop();
        if (node -> r) {
            stack.push(node -> r);
        }
        
        if (node -> l) {
            stack.push(node -> l);
        }
    }
    /**
     int vec[] = {10,8,12,7,9,11,13};
     TN* root = NULL;
     create_TN_tree(root, vec, 7, 0);
     
     previous_walk_tree_no_recursive(root);
     */
}

#pragma mark 中序遍历二叉树(非递归)
void middle_walk_tree_no_recursive(TN* head){
    
    std::stack<TN*> stack;
    while (head || !stack.empty()) {
        
        while (head) {
            
            stack.push(head);
            head = head -> l;
        }
        
        TN* node = stack.top();
        NSLog(@"%s,%d",__func__,node -> val);
        stack.pop();
        
        head = node -> r;
        
    }
    /**
     int vec[] = {10,8,12,7,9,11,13};
     TN* root = NULL;
     create_TN_tree(root, vec, 7, 0);
     
     middle_walk_tree_no_recursive(root);
  
     */
}

#pragma mark 后序遍历二叉数(非递归)
void after_walk_tree_no_recursive(TN* head){
    
    if (!head) {
        return;
    }
    
    std::stack<TN*> stack;
    stack.push(head);
    TN* last = head;
    
    while (!stack.empty()) {
        
        TN* p = stack.top();
        if ((p -> l == NULL && p -> r == NULL) ||(last == p -> l && p -> r == NULL) || last == p -> r ) {
            NSLog(@"%s,%d",__func__,p -> val);
            last = p;
            stack.pop();
        }else{
            
            if (p -> r) {
                stack.push(p -> r);
            }
            
            if (p -> l) {
                stack.push(p -> l);
            }
        }
    }
    /**
     int vec[] = {10,8,12,7,9,11,13};
     TN* root = NULL;
     create_TN_tree(root, vec, 7, 0);
     
     previous_walk_tree_no_recursive(root);
     middle_walk_tree_no_recursive(root);
     after_walk_tree_no_recursive(root);
     exchange_left_right_tree(root);
     middle_walk_tree_no_recursive(root);
     */
}
#pragma mark 后序遍历二叉数(非递归)连续将一个节点压入栈两次
void after_walk_tree_no_recursive_continue_two_push(TN* head){
    
    if (!head) {
        return;
    }
    
    stack<TN*> stack;
    stack.push(head);
    stack.push(head);
    
    while (!stack.empty()) {
        
        TN* node = stack.top();
        stack.pop();
        //说明左右孩子还没被访问过
        if (!stack.empty() && node == stack.top()) {
            
            if (node -> r) {
                stack.push(node -> r),stack.push(node -> r);
            }
            
            if (node -> l) {
                stack.push(node -> l),stack.push(node -> l);
            }
        }else{
           
             NSLog(@"%s,%d",__func__,node -> val);
        }
    }
    /****
     int vec[] = {10,8,12,7,9,11,13};
     TN* root = NULL;
     create_TN_tree(root, vec, 7, 0);
     
     after_walk_tree_no_recursive_continue_two_push(root);
     */
    
}

#pragma mark 二叉树左右子数交换
void exchange_left_right_tree(TN* head){
    
    if (!head) {
        return;
    }
    
    if (!head -> l || !head -> r) {
        return;
    }
    
    TN* p = head -> l;
    head -> l = head -> r;
    head -> r = p;
    
    exchange_left_right_tree(head -> l);
    exchange_left_right_tree(head -> r);
    
    /**
     int vec[] = {10,8,12,7,9,11,13};
     TN* root = NULL;
     create_TN_tree(root, vec, 7, 0);
     
     previous_walk_tree_no_recursive(root);
     middle_walk_tree_no_recursive(root);
     after_walk_tree_no_recursive(root);
     exchange_left_right_tree(root);
     middle_walk_tree_no_recursive(root);
     */
}

#pragma mark 芝之形打印二叉树
void print_binary_tree_ZZZZZ(TN* head){
    std::stack<TN*> zStack[2];
    
    int currentLevel = 0;
    int nextLevel = 1;
    zStack[currentLevel].push(head);
    while (!zStack[currentLevel].empty() || !zStack[nextLevel].empty()) {
        
        TN* node = zStack[currentLevel].top();
        zStack[currentLevel].pop();
        if (node) {
            printf("%d ",node -> val);
            if (currentLevel == 0) {
                zStack[nextLevel].push(node -> l);
                zStack[nextLevel].push(node -> r);
            }else{
                zStack[nextLevel].push(node -> r);
                zStack[nextLevel].push(node -> l);
            }
        }
        
        if (zStack[currentLevel].size() == 0) {
            currentLevel = 1 - currentLevel;
            nextLevel = 1 - nextLevel;
        }
    }
    
    /***
     TN* root = NULL;
     int vec[] = {1,2,3,4,5,6,7,8,9};
     
     create_TN_tree(root, vec, sizeof(vec) / sizeof(int), 0);
     print_binary_tree_ZZZZZ(root);
     */
}
    
#pragma mark 先序打印二叉树
void printTNPreOrder(struct TN* head){
    if (head == NULL) {
        return;
    }
    
    NSLog(@"%d ",head -> val);
    printTNPreOrder(head -> l);
    
    printTNPreOrder(head -> r);
}

    
#pragma mark 二叉搜索树转换为双向链表 采用队列的形式 (队列)
void insertOrderToQueue(TN* head,std::queue<TN*>& queue){
    if (!head) {
        return;
    }
    
    if (head -> l) {
        insertOrderToQueue(head -> l,queue);
    }
    
    queue.push(head);
    
    if (head -> r) {
        insertOrderToQueue(head -> r,queue);
    }
}
    
TN* search_binary_tree_convert_double_link(TN* head){
    
    if (!head) {
        return NULL;
    }
    
    std::queue<TN*> queue;
    insertOrderToQueue(head, queue);
    
    if (queue.empty()) {
        return NULL;
    }
    
    TN* doubleListHead = queue.front();
    queue.pop();
    doubleListHead -> l = NULL;
    doubleListHead -> r = NULL;
    
    TN* p =  doubleListHead;
    while (!queue.empty()) {
        
        TN* node = queue.front();
        queue.pop();
        
        p -> r = node;
        node -> l = p;
        
        p = node;
        
    }
    
    p -> r = NULL;
    return doubleListHead;
    /**
     TN* root = NULL;
     int vec[] = {10,8,12,7,9,11,13};
     
     create_TN_tree(root, vec, sizeof(vec) / sizeof(int), 0);
     TN* head = search_binary_tree_convert_double_link(root);
     while (head) {
     NSLog(@"%d ",head -> val);
     head = head -> r;
     }
     */
}

#pragma mark 二叉搜索树转换为双向链表 采用队列的形(递归)
TN* retun_double_link_from_tree(TN* root){
    
    if (!root) {
        return NULL;
    }
    
    TN* pHead = NULL;
    search_binary_tree_convert_double_link2(root,&pHead);
    
    while (pHead && pHead -> l) {
        pHead = pHead -> l;
    }
    
    return pHead;
    
}


void search_binary_tree_convert_double_link2(TN* root,TN** pLastNode){
    if (!root) {
        return;
    }
    
    if (root -> l) {
        search_binary_tree_convert_double_link2(root -> l,pLastNode);
    }
    
    root -> l = *pLastNode;
    
    if (*pLastNode) {
        (*pLastNode) -> r = root;
    }
    
    *pLastNode = root;
    if (root -> r) {
        search_binary_tree_convert_double_link2(root -> r,pLastNode);
    }
    /**
     TN* root = NULL;
     int vec[] = {10,8,12,7,9,11,13};
     
     create_TN_tree(root, vec, sizeof(vec) / sizeof(int), 0);
     //walk_tree(root);
     TN* head = retun_double_link_from_tree(root);
     while (head) {
     NSLog(@"%d ",head -> val);
     head = head -> r;
     }
     **/
}

#pragma mark 在数组中出现次数超过一半的数字
int more_than_half_num_2(vector<int> vec){
    if (vec.empty()) {
        return 0;
    }
    
    int result = vec[0];
    int times = 1;
    for (int index = 1; index < vec.size(); index++) {
        
        if (times == 0) {
            
            result = vec[index];
            times = 1;
            
        }else if(result == vec[index]) {
    
            times++;
        }else{
            times--;
        }
    }
    
    times = 0;
    for (std::vector<int>::iterator iter = vec.begin(); iter != vec.end(); iter++) {
        if(result == *iter){
            times++;
        }
    }
    
    return (times > (vec.size() >> 1)) ? result : 0;
    /***
     std::vector<int> vec;
     vec.push_back(1);
     vec.push_back(2);
     vec.push_back(2);
     vec.push_back(2);
     vec.push_back(2);
     vec.push_back(5);
     vec.push_back(2);
     vec.push_back(6);
     vec.push_back(7);
     int ret = more_than_half_num_2(vec);
     */
}

#pragma mark 将选定一个数,然后小于的数字移动到左边,大于的数字移动到右边
void xl_swap(int* p,int* q){
    int temp = *p;
    *p = *q;
    *q = temp;
}

int xl_partition(int* vec,int len,int start,int end){
    if (!vec || len <= 0) {
        return -1;
    }
    
    int small = start - 1;
    
    int random_index = random() % (end - start) + start;
    xl_swap(&vec[random_index], &vec[end]);
    for (int index = start; index < end; index++){
        
        if (vec[index] < vec[end]) {
            small++;
            if (small != index) {
                xl_swap(&vec[index],&vec[small]);
            }
        }
    }
    
    small++;
    xl_swap(&vec[end], &vec[small]);
    
    return small;
}

#pragma mark 在数组中出现次数超过一半的数字
//int more_than_half_num_1(int* vec,int len){
//    int middle = len >> 1;
//
//    int index  = xl_partition(vec, len, 0, len - 1);
//    while (index != middle) {
//
//        if (index > middle){
//            index = xl_partition(vec, index + 1, 0, index);
//        }else{
//            index = xl_partition(vec, len - index, index, len - 1);
//        }
//    }
//
//    return vec[index];
//
//}



#pragma mark 二维数组查找,从左到右,从上到下递增排序
bool tow_dimensional_vector(int vec[][4],int search_value,int rows ,int columns){
    
    if (!vec || rows <= 0 || columns <= 0) {
        return false;
    }
    
    int row = 0;
    int col = columns - 1;
    
    while (row <= rows - 1 && col >= 0) {
        
        if (vec[row][col] == search_value) {
            
            return true;
        }else if(vec[row][col] < search_value){
            row++;
        }else{
            col--;
        }
    }
    
    return false;
    /**
     int vec[][4] = {1,2,3,4,
     3,4,7,8,
     4,12,13,18,
     10,15,14,20
     };
     
     bool ret = tow_dimensional_vector(vec, 1, 4, 4);
     */
}
#pragma mark 斐波那契数(递归)
int fabonaci_recursive(int n){
    
    if (n == 0) {
        return 0;
    }
    
    if(n == 1){
        return 1;
    }
    
    return fabonaci_recursive(n - 1) + fabonaci_recursive(n - 2);
}

#pragma mark 斐波那契数(非递归) - 动态规划算法
int fabonaci_dynamic_programming(int n){

    int f1 = 0;
    int f2 = 1;
    int f3 = 0;
    if (n == 0) {
        return f1;
    }
    
    if (n == 1) {
        return f2;
    }
    
    for (int index = 0; index < n - 1; index++) {
        f3 = f2 + f1;
        f1 = f2;
        f2 = f3;
    }
    
    return f3;
}

#pragma mark 1,3,5 最少的硬币凑 m元(greedy algorithm)
int greedy_min_count(int m){
    
    int value[] = {1,3,5};
   
    int result_count = 0;
    for (int i = sizeof(value)/sizeof(int) - 1; i >= 0; i--) {
        
        int min_count = m / value[i];
        m -= min_count * value[i];
        result_count += min_count;
        if (m == 0) {
            break;
        }
    }
    
    return result_count;
}

#pragma mark 1,3,5 最少的硬币凑 m元(dynamic programming algorithm)
int dynamic_programming_min_count(int m){
    
    int value[] = {1,3,5};
    int* temp = new int[m + 1];
   
    for (int i = 1; i <= m; i++) {
        temp[i] = i;
    }
    
    for (int i = 1; i <= m; i++) {
        for (int j = 0; j < sizeof(value) / sizeof(int) ; j++) {
            if (i >= value[j] && temp[i - value[j]] + 1 < temp[i]) {
                temp[i] = temp[i - value[j]] + 1;
            }
        }
    }
    
    return temp[m];
    /***    int c1 = greedy_min_count(777);
     int c2 = dynamic_programming_min_count(777);*/
}

#pragma mark  剪短绳子每一小块,乘积最大(dynamci)
int cut_rope_max_dynamic(int len){
    
    if (len <= 1) {
        return 0;
    }
    
    if (len == 2) {
        return 1;
    }
    
    if (len == 3) {
        return 2;
    }
    
    int* value = new int[len + 1];
    //长度为2的最大积
    value[1] = 1;
    //长度为3的最大积
    value[2] = 2;
    //长度为4的最大积
    value[3] = 3;
    
    for (int i = 4; i <= len; i++) {
        int max = 0;
        for (int j = 1; j <= i / 2; j++) {
            value[i] = value[j] * value[i - j];
            max = value[i] > max ? value[i]:max;
            value[i] = max;
        }
    }
    
    int max_value = value[len];
    delete [] value;
    
    return max_value;
}

#pragma mark  剪短绳子每一小块,乘积最大(greedy)
int64_t cut_rope_max_greedy(int len){
    
    if (len <= 1) {
        return 0;
    }
    
    if (len == 2) {
        return 1;
    }
    
    if (len == 3) {
        return 2;
    }
    
    int time_of_3 = len / 3;
    
    if (time_of_3 * 3 + 1 == len) {
        time_of_3--;
    }
    
    int time_of_2 = (len - time_of_3 * 3) >> 1;
    
    return (int)pow(3, time_of_3) * (int)pow(2, time_of_2);
    /** int64_t result1 = cut_rope_max_dynamic(40);
     int64_t result2 = cut_rope_max_greedy(40);
     int a = (int)(test_power(3, 40));*/
    
}


#pragma mark 有序数组中,两个数字之和为m,并输出这两个数
void print_two_element_sum(int vec[],int len,int m){
    
    if (!vec || len == 0) {
        return;
    }
    
    int low = 0;
    int high = len - 1;
    
    while (low < high) {
        if (vec[low] + vec[high] == m) {
            low++;
            NSLog(@"%d + %d sum is %d",vec[low],vec[high],m);
        }else if(vec[low] + vec[high] < m){
            low++;
        }else{
            high--;
        }
    }
    /**
     int vec[] = {1,2,3,4,9,10,11,12};
     print_two_element_sum(vec, sizeof(vec)/sizeof(int), 13);
     */
}

#pragma mark 二进制中1的个数(method 1)
int binary_count_one(int m){
    
    int count = 0;
    while (m) {
        m = m & (m - 1);
        count++;
    }
    
    return count;
}

#pragma mark 二进制中1的个数(method 2)
int binary_count_one_2(int m){
    
    int count = 0;
    int index = 32;
    while (index > 0) {
      
        if ((m & 0x1) == 1) {
            count++;
        }
        
        m = m >> 1;
        index--;
    }
    return count;
}

#pragma mark 数组中唯一不重复的两个元素
void two_element_no_repeat(int* vec,int len){
    
    if (!vec || len <= 0) {
        return;
    }
    
    int result = 0;
    for (int i = 0; i < len ; i++) {
        result = result ^ vec[i];
    }
    
    int min_low_1_index = 0;
    int flag = 0x1;
    
    while ((result & flag) == 0) {
        flag = flag << 1;
        min_low_1_index++;
    }
    
    int num1 = 0;
    int num2 = 0;
    for (int i = 0; i < len; i++) {
        
        if (((vec[i] >> min_low_1_index) & 0x01) == 1) {
            num1 = num1 ^ vec[i];
        }else{
            num2 = num2 ^ vec[i];
        }
    }
    
    NSLog(@"diff1:%d,diff2:%d",num1,num2);
    /**
     int vec[] = {1,2,4,5,5,4,1,2,7,9,9,10};
     two_element_no_repeat(vec, sizeof(vec) / sizeof(int));
     *
     */
}

#pragma mark 数组中唯一一个整形元素,其他整形出现3次
void vector_just_appear_once(int* vec,int len){
    
    if (!vec || len <= 0) {
        return;
    }
    
    int bits_sum[32];
    memset(bits_sum, 0, sizeof(bits_sum));
    
    int index = 0;
    int flag = 0x1;
    while (index < 32) {
        
        for (int i = 0; i < len; i++) {
            int result = vec[i] & flag;
            result = result >> index;
            bits_sum[index] += result;
        }
        
        flag = flag << 1;
        index++;
    }
    
    int once_value = 0;
    for (int i = 31; i >= 0; i--) {
        
        once_value = once_value << 1;
        once_value = once_value | (bits_sum[i] % 3);
    }
    
    NSLog(@"appear once value:%d",once_value);
    /**
     int vec[] = {999,999,2,29,1,1,1,2,2,1023,3,3,3,1023,1023,999};
     vector_just_appear_once(vec, sizeof(vec) / sizeof(int));
     */
}

#pragma mark 调整数组顺序使奇数位于偶数前面
void adjust_odd_even(int* vec,int len){
    
    if (!vec || len <= 0) {
        return;
    }
    
    int low = 0;
    int high = len - 1;
    
    while (low < high) {
        while (low < high && (vec[high] & 0x1) != 1) {
            high--;
        }
        
        while (low < high && (vec[low] & 0x1) == 1) {
            low++;
        }
        
        if (low < high) {
            int temp = vec[high];
            vec[high] = vec[low];
            vec[low] = temp;
        }
    }
    /**
     int vec[] = {999,999,2,29,1,1,1,2,2,1023,3,3,3,1023,1023,999};
     adjust_odd_even(vec, sizeof(vec)/sizeof(int));
     int breakp = 0;
     */
}

#pragma mark 旋转数组的最小数字 5 8 9 1 2 3
void min_value_rotating_vec(int* vec,int len){
    
    if (!vec || len <= 0) {
        return;
    }
    
    int low = 0;
    int high = len - 1;

    while (low < high) {
        
        if (high - low == 1) {
            NSLog(@"min_value_rotating_vec:%d",vec[high]);
            return;
        }
        int middle = (high + low) >> 1;
        if (vec[middle] > vec[low]) {
            low = middle;
        }else if(vec[middle] < vec[high]){
            high = middle;
        }else if(vec[middle] == vec[high] && vec[low] == vec[high]){ //特殊情况
            int min = vec[low];
            for (int i = low + 1; i < high; i++) {
                if (vec[i] < min) {
                    min = vec[i];
                }
            }
            
            NSLog(@"min_value_rotating_vec:%d",min);
            return;
        }
    }
    /**
        int vec[] = {5,8,9,10,12,1,2,3,5,9};
        int vec[] = {1,1,1,1,0,1,1};
     */
}
#pragma mark 连续子数组最大和
int continue_sub_vec_max_value(int* vec,int len){

    if (!vec || len <= 0) {

        return -1;
    }

    int low = 0;
    int current_max_value = vec[low];
    int max_value = vec[low];
    while (low < len) {
        
        if (current_max_value < 0) {
            
            current_max_value = vec[low];
        }else{
            current_max_value += vec[low];
        }
    
        if (current_max_value > max_value) {
            max_value = current_max_value;
        }
        
        low++;
    }
    
    return max_value;
    /**
     int vec[] = {1,-2,3,10,-4,7,2,-5};
     int max = continue_sub_vec_max_value(vec, sizeof(vec)/sizeof(int));
     */
}

#pragma mark 求一个字符串只出现一次的字符
void print_only_once_character(char* str){
    
    if (!str) {
        return;
    }
    
    int single_hash_table[256];
    memset(single_hash_table, 0, sizeof(single_hash_table));
    
    char* p = str;
    while (*p != '\0') {
        single_hash_table[*p]++;
        p++;
    }
    
    int index = 0;
    while (index < 256) {
        
        if (single_hash_table[index] == 1) {
            NSLog(@"%c",index);
        }
        index++;
    }
    /**
         print_only_once_character("abcdabcefg");
     **/
}

#pragma mark 字符串与字符模式匹配(正则表达式)
bool match(char* str, char* pattern){
    // 指针为空,返回false
    if(str == NULL || pattern == NULL){
        return false;
    }
    return matchCore(str, pattern);
}

bool matchCore(char* str, char* pattern){
    // 字符串和模式串都运行到了结尾,返回true
    if(*str == '\0' && *pattern == '\0'){
        return true;
    }
    // 字符串没有到结尾,模式串到了,则返回false
    // 模式串没有到结尾,字符串到了,则根据后续判断进行,需要对'*'做处理
    if((*str != '\0' && *pattern == '\0')){
        return false;
    }
    // 如果模式串的下一个字符是'*',则进入状态机的匹配
    if(*(pattern + 1) == '*'){
        // 如果字符串和模式串相等,或者模式串是'.',并且字符串没有到结尾,则继续匹配
        if(*str == *pattern || (*pattern == '.' && *str != '\0')){
            // 进入下一个状态,就是匹配到了一个
            return matchCore(str + 1, pattern + 2) ||
            // 保持当前状态,就是继续那这个'*'去匹配
            matchCore(str + 1, pattern) ||
            // 跳过这个'*'
            matchCore(str, pattern + 2);
        }
        // 如果字符串和模式串不相等,则跳过当前模式串的字符和'*',进入新一轮的匹配
        else{
            // 跳过这个'*'
            return matchCore(str, pattern + 2);
        }
    }
    // 如果字符串和模式串相等,或者模式串是'.',并且字符串没有到结尾,则继续匹配
    if(*str == *pattern || (*pattern == '.' && *str != '\0')){
        return matchCore(str + 1, pattern + 1);
    }
    return false;
    /**
     bool ret1 = match("aaa", "a.a");
     bool ret2 = match("aaa", "ab*ac*a");
     bool ret3 = match("aaa", "aa.a");
     bool ret4 = match("aaa", "ab*a");
     */
}

#pragma mark 回溯法 搜索矩阵中是否存在一条路径
bool has_path(char* matrix,int rows,int cols,char* str,bool visited[]){
    if (!matrix || rows <= 1 || cols <= 1 || !str) {
        return false;
    }
    
    bool hasPath = false;
    memset(visited, 0, rows * cols);
    
    for (int i = 0; i < rows; i++) {
        
        for (int j = 0; j < cols; j++) {

            hasPath = has_path_core(matrix, i, j,rows,cols,visited,str);
            
            if (hasPath) {
                return true;
            }
             memset(visited, 0, rows * cols);
        }
    }
    
    return hasPath;
}

bool has_path_core(char* matrix,int row,int col,int rows,int cols,bool* visited,char* str){
    
    if (*str == '\0') {
        return true;
    }
    
    bool has_path = false;
    
    if (row >= 0 && col >= 0 && row < rows && col < cols && *str == matrix[row * cols + col] && !visited[row * cols + col]) {
        
        visited[row * cols + col] = true;
        has_path = has_path_core(matrix, row - 1, col,rows,cols, visited,str + 1)
                || has_path_core(matrix, row + 1, col,rows,cols, visited,str + 1)
                || has_path_core(matrix, row, col - 1,rows,cols, visited,str + 1)
                || has_path_core(matrix, row, col + 1,rows,cols, visited,str + 1);
        
        if (!has_path) {
            visited[row * cols + col] = false;
        }
        
    }
    
    return has_path;
    /**
     char matrix[] = {
     
     'a','b','c','d',
     'e','f','g','h',
     'i','j','k','l',
     'm','n','o','p'
     };
     
     bool visited[16];
     bool ret = has_path(matrix, 4, 4, "abcdhlponmiefgkj",visited);
     */
    
}

#pragma mark 机器人运动范围



#pragma mark 是否丑数
bool is_ugly(int n){
    
    while (n % 2 == 0) {
        n = n / 2;
    }
    
    while (n % 3 == 0) {
        n = n / 3;
    }
    
    while (n % 5 == 0) {
        n = n / 5;
    }
    
    return n == 1 ? true : false;
}

int get_ugly_number(int index){
    
    if (index <= 0) {
        return 0;
    }
    int count = 0;
    int number = 0;
    while (count < index) {
        
        number++;
        if (is_ugly(number)) {
            count++;
        }
    }
    
    return number;
}

int GetUglyNumber_Solution2(int index){
    if(index <= 0)
        
        return 0;
    
    int *pUglyNumbers = new int[index];
    
    pUglyNumbers[0] = 1;
    
    int nextUglyIndex = 1;
    
    int *pMultiply2 = pUglyNumbers;
    
    int *pMultiply3 = pUglyNumbers;
    
    int *pMultiply5 = pUglyNumbers;
    while(nextUglyIndex < index)
        
    {
        
        int temp = *pMultiply2 * 2 < *pMultiply3 * 3 ? *pMultiply2 * 2:*pMultiply3 * 3;
        
        int min = temp < *pMultiply5 * 5 ? temp : *pMultiply5 * 5;
        
        pUglyNumbers[nextUglyIndex] = min;
    
        
        while(*pMultiply2 * 2 <= pUglyNumbers[nextUglyIndex])
            
            ++pMultiply2;
        
        while(*pMultiply3 * 3 <= pUglyNumbers[nextUglyIndex])
            
            ++pMultiply3;
        
        while(*pMultiply5 * 5 <= pUglyNumbers[nextUglyIndex])
            
            ++pMultiply5;
        
        ++nextUglyIndex;
        
    }
    
    int ugly = pUglyNumbers[nextUglyIndex - 1];
    
    delete[] pUglyNumbers;
    
    return ugly;
}

#pragma mark 计数排序
template <typename T>
void count_sort(T* vec,int len){

    if (!vec || len <= 0) {
        return;
    }

    T min = vec[0];
    T max = vec[0];
    for (int i = 1; i < len; i++) {

        if (vec[i] < min) {
            min = vec[i];
        }

        if (vec[i] > max) {
            max = vec[i];
        }
    }

    T* p = new T[max - min + 1];
    memset(p, 0, sizeof(int) * (max - min + 1));
    for (int i = 0; i < len; i++) {
        *(p + *(vec + i) - min) = *(p + *(vec + i) - min) + 1;
    }

    for (T i = min; i <= max; i++) {

        while (*(p + i - min) > 0) {
            NSLog(@"%d",i);
            *(p + i - min) = *(p + i - min) - 1;

        }
    }
}

// 求出数组中最大数的位数的函数
int MaxBit(vector<int> input){
    // 数组最大值
    int max_data = input[0];
    for (int i = 1; i < input.size(); i++){
        if (input[i] > max_data){
            max_data = input[i];
        }
    }
    
    // 数组最大值的位数
    int bits_num = 0;
    while (max_data){
        bits_num++;
        max_data /= 10;
    }
    
    return bits_num;
}

// 取数xxx上的第d位数字
int digit(int num, int d){
    int pow = 1;
    while (--d > 0){
        pow *= 10;
    }
    return num / pow % 10;
}

#pragma mark 基数排序
vector<int> radixSort(vector<int> input, int n){
    // 临时数组,用来存放排序过程中的数据
    vector<int> bucket(n);
    // 位记数器,从第0个元素到第9个元素依次用来记录当前比较位是0的有多少个...是9的有多少个数
    vector<int> count(10);
   
    for (int d = 1; d <= MaxBit(input); d++){
        // 计数器清0
        for (int i = 0; i < 10; i++){
            count[i] = 0;
        }
    
        for (int i = 0; i < n; i++){
            count[digit(input[i],d)]++;
        }

        for (int i = 1; i < 10; i++){
            count[i] += count[i - 1];
        }
    
        for (int i = n - 1; i >= 0; i--){
            int k = digit(input[i], d);
            bucket[count[k] - 1] = input[i];
            count[k]--;
        }
        // 临时数组复制到 input 中
        for (int i = 0; i < n; i++){
            input[i] = bucket[i];
        }
    }
    
    return input;
    /**
     std::vector<int>vec;
     vec.push_back(11);
     vec.push_back(12);
     vec.push_back(10);
     vec.push_back(1);
     vec.push_back(7);
     vec.push_back(1002);
     vec.push_back(102);
     vec.push_back(100);
     vec.push_back(91);
     vec.push_back(81);
     vec.push_back(71);
     
     vector<int> vec1 = radixSort(vec, vec.size());
     for (std::vector<int>::iterator iter = vec1.begin(); iter != vec1.end(); ++iter) {
     NSLog(@"%d",*iter);
     }
     */
}

#pragma mark 连续正数和为S
void continue_sum_equal_s(int s){
 
    
    int low = 0;
    int high = 1;
    
    while (low < high) {
        
        int sum = 0;
        for (int i = low; i <= high; i++) {
            sum += i;
        }
        
        if (sum == s) {
           
            for (int i = low; i <= high; i++) {
                NSLog(@"%s     %d",__func__,i);
            }
            low++;
            high++;
             NSLog(@"====");
            
        }else if(sum < s){
            high++;
        }else{
            low++;
        }
    }
}

vector<vector<int> > FindContinuousSequence(int sum) {
    vector<vector<int> > result;
    // 高位指针和低位指针
    int phigh = 2, plow = 1;
    
    // 终止条件是phigh等于sum
    while(phigh > plow){
        // 当前和,使用求和公式s = (a+b) * n / 2
        int curSum = (plow + phigh) * (phigh - plow + 1) >> 1;
        if(curSum < sum){
            phigh++;
        }
        if(curSum == sum){
            vector<int> temp;
            for(int i = plow; i <= phigh; i++){
                temp.push_back(i);
            }
            result.push_back(temp);
            plow++;
        }
        if(curSum > sum){
            plow++;
        }
    }
    return result;
}

#pragma mark (0 ~ n)数组中查找重复的数字并返回其中一个(时间复杂度O(n),空间复杂度O(n))
int vector_search_duplicate_vector(int* vec,int len){
    
    if (!vec || len <= 0) {
        return -1;
    }
    
    std::vector<int> temp_vector(7,0);
    
    for (int i = 0; i < len; i++) {
        
        temp_vector[vec[i]]++;
        
        if (temp_vector[vec[i]]  == 2) {
            return vec[i];
        }
    }
    
    return -1;
}

#pragma mark (0 ~ n) 数组中查找重复的数字并返回其中一个(时间复杂度O(n),空间复杂度O(1))
int vector_search_duplicate_swap(int* vec,int len){
   
    if (!vec || len <= 0) {
        return -1;
    }
    
    for (int i = 0; i < len; i++) {
        
        while (vec[i] != i) {
            
            if (vec[i] == vec[vec[i]]) {
                return vec[i];
            }
            
            int temp = vec[i];
            vec[i] = vec[temp];
            vec[temp] = temp;
        }
    }
    
    
    return -1;
    
}

#pragma mark (0 ~ n) 数组中查找重复的数字并返回其中一个(时间复杂度O(nlogn),空间复杂度O(1))
int vector_search_duplicate_binary(int* vec,int len){
    
    if (!vec || len <= 0) {
        return -1;
    }
    
    int start = 0 ;
    int end = len - 1;
    
    while (start <= end) {
       
        int middle = ((end - start) >> 1) + start;
      
        
        int count = 0;
        for (int i = 0; i < len; i++) {
            
            int value = vec[i];
            if (value >= start && value <= middle) {
                count++;
            }
        }
        
        if (start == end) {
            if (count > 1) {
                return start;
            }else{
                break;
            }
        }
        
        if (count > (middle - start + 1)) {
            
            end = middle;
            
        }else{
            
            start = middle + 1;
        }
    }
    
    return -1;
    
}


#pragma mark 二分查找(递归)
int binary_search_recursive(int vec[],int key,int start,int end){
    
    if (!vec || start > end) {
        return -1;
    }
    
    int middle = (start + end) >> 1;
    
    if (vec[middle] == key) {
        return middle;
    }else if(vec[middle] < key){
        return binary_search_recursive(vec, key, middle + 1, end);
    }else{
        return binary_search_recursive(vec, key, start, middle - 1);
    }
}

#pragma mark 二分查找(顺序)
int binary_search_in_order(int vec[],int key,int start,int end){
    
    if (!vec || start > end) {
        return -1;
    }
    
    while (start <= end) {
        
        int middle = (start + end) >> 1;
        
        if (vec[middle] == key) {
            return middle;
        }else if(vec[key] < key){
            start = middle + 1;
        }else{
            end = middle - 1;
        }
    }
    
    return -1;
    /** int vec[] = {1,2,3,4,5,7,8,9,10,13,14,15,25,35,46};
     int left_index = binary_search_recursive(vec, 1,0,sizeof(vec) / sizeof(int) - 1);
     int right_index = binary_search_in_order(vec,1, 0, sizeof(vec) / sizeof(int) - 1);
     */
}

#pragma mark 在字符串中删除特定的字符
char* delete_specify_character(char* source,const char* specify){
    
    if (!source || !specify) {
        return NULL;
    }
    
    int single_tables[256];
    memset(single_tables, 0, sizeof(single_tables));
    
    while (*specify != '\0') {
        single_tables[*specify]++;
        specify++;
    }
    
    char* pDest = source;
    char* pTemp = source;
    while (*pTemp != '\0') {
        
        if (single_tables[*pTemp] == 0) {
            *pDest = *pTemp;
            pDest++;
        }
        pTemp++;
    }
    
    *pDest = '\0';
    
    return source;
    /**
     char source[] = {'a','b','c','d','e','f','g','h','i','s','s','s','e','e','g','g','g'};
     const char* specify = "absg";
     char* result = delete_specify_character(source, specify);
     **/
}

#pragma mark 左旋转字符串 时间辅助度O(n) 空间辅助度O(1)
char* left_rotate_str(char* str,int m){

    if (!str) {
        return NULL;
    }
    
    size_t len = strlen(str);
    if (m > len) {
        return NULL;
    }
    
    reverse_str(str, 0, m - 1);
    reverse_str(str, m, len - 1);
    reverse_str(str, 0, len - 1);
    
    return str;
}

void reverse_str(char* str,size_t start,size_t end){
    
    if (!str || end <= start) {
        return;
    }
    
    while (start < end) {
        char temp = *(str + start);
        *(str + start) = *(str + end);
        *(str + end) = temp;
        
        start++;
        end--;
    }
    /***
     char source[] = {'a','b','c','d','e','f'};
     char* result = left_rotate_str(source, 2);
     size_t len = strlen(result);
     char buffer[256];
     memcpy(buffer, result, len + 1);
     */
}

#pragma mark 字符串转换为整型
bool g_invalid = false;
int str_to_int(char* str){
    
    if (!str) {
        g_invalid = true;
        return -1;
    }
    
    bool minus = false;
    if (*str == '-') {
        minus = true;
        str++;
    }else if(*str == '+'){
        minus = false;
        str++;
    }
    
    int result = 0;
    while (*str != '\0') {
        
        int digit = *str - '0';
        if (digit >= 0 && digit <= 9) {
            result = result * 10 + digit;
            if (result >= std::numeric_limits<int>::max()) {
                result = -1;
                g_invalid = true;
                return result;
            }
        }else {
            g_invalid = true;
            return -1;
        }
        str++;
    }
    
    if (minus) {
        result = 0 - result;
    }
    
    return result;
    /**
        int ret = str_to_int("+2345609");
     */
}

#pragma mark 获取指定排序数组中 某数的连续个数
int get_left_index(int vec[],int key,int len,int start,int end){
    
    if(!vec || start > end){
        return -1;
    }
    
    if (start == end) {
        return start;
    }
    
    int middle = (start + end) >> 1;
    
    if (vec[middle] == key) {
        
        if(((middle - 1 >= start) && vec[middle - 1] != key) || middle == 0){
            return middle;
        }else{
            end = middle - 1;
        }
    }else if(vec[middle] < key){
        start = middle + 1;
    }else{
        end = middle - 1;
    }
    
    return get_left_index(vec, key,len, start, end);
}

int get_right_index(int vec[],int key,int len,int start,int end){
    
    if(!vec || start > end){
        return -1;
    }
    
    if (start == end) {
        return start;
    }
    
    int middle = (start + end) >> 1;
    
    if (vec[middle] == key) {
        
        if( ((middle + 1 <= end ) && vec[middle + 1] != key) || middle == len - 1){
            return middle;
        }else{
            start = middle + 1;
        }
    }else if(vec[middle] < key){
        start = middle + 1;
    }else{
        end = middle - 1;
    }
    
    return get_right_index(vec, key,len,start, end);
    /**
     int vec[] = {1,2,3,3,3,3,3,3,3,3,4,5,5,5,6};
     int left_index = get_left_index(vec, 3,sizeof(vec) / sizeof(int),0,sizeof(vec) / sizeof(int) - 1);
     int right_index = get_right_index(vec,3, sizeof(vec) / sizeof(int),0, sizeof(vec) / sizeof(int) - 1);
     */
}

#pragma  mark 最低公共组先(没有子节点指向父亲节点)
TN* lowest_common_ancestor(TN* root,int value ,int other_value){
    
    if (!root) {
        return NULL;
    }
    
    TN* resultNode = NULL;
    
    std::vector<TN*> vec;
    std::deque<TN*> one_deque;
    std::deque<TN*> other_deque;
    
    iterator_tree(root,vec,one_deque,value);
    iterator_tree(root,vec,other_deque,other_value);
    
    TN* p = NULL;
    TN* q = NULL;

    while (one_deque.size() > 0 || other_deque.size() > 0) {
    
        if (!one_deque.empty()) {
            
            p = one_deque.front();
            one_deque.pop_front();
        }
        
        if (!other_deque.empty()) {
            q = other_deque.front();
            other_deque.pop_front();
        }
        
        if (p -> val != q -> val) {
            
            return resultNode;
        }
        
        resultNode = p;
    }
    
    return resultNode;
}

void iterator_tree(TN* root, std::vector<TN*> vec,std::deque<TN*>& deque,int value){
    
    if (!root) {
        return ;
    }
    
    vec.push_back(root);
    if (root -> val == value) {
        
        for (std::vector<TN*>::iterator iter = vec.begin() ; iter != vec.end() ;iter++) {
            deque.push_back(*iter);
        }
    }
    
    iterator_tree(root -> l,vec,deque,value);
    iterator_tree(root -> r,vec,deque,value);

    vec.pop_back();
    /***
     int vec[] = {100,1,8,0,2,3,5,7,10,99,11,92,109};
     //heap_sort(vec, sizeof(vec)/sizeof(int));
     TN* root = NULL;
     create_TN_tree(root, vec, sizeof(vec)/sizeof(int), 0);
     lowest_common_ancestor(root, 109, 92);
     */
}

#pragma  mark 最低公共组先(排序二叉树)
TN* lowest_common_ancestor_tree_in_order(TN* root,int value ,int other_value){
    
    if (!root) {
        return NULL;
    }
    
    TN* p = NULL;
    while (root) {
        
        if ((root -> val <= value && root -> val >= other_value) || (root -> val <= other_value && root -> val >= value)) {
            return root;
        }else if(root -> val < value && root -> val < other_value){
            root = root -> r;
        }else{
            root = root -> l;
        }
    }
    
    return p;
    /**
     int vec[] = {100,88,108,77,99,106,125};
     TN* root = NULL;
     create_TN_tree(root, vec, sizeof(vec)/sizeof(int), 0);
     TN* p = lowest_common_ancestor_tree_in_order(root, 108, 125);
     */
}
#pragma  mark 最低公共组先(子节点有指向父节点指针)
TN* lowest_common_ancestor_tree_sub_node_pointer_father(TN* root,int value ,int other_value){
    
    if(!root){
        return NULL;
    }

    TN* p = NULL;
    find_current_value_node(root,p,value);
    TN* q = NULL;
    find_current_value_node(root,q,other_value);
    
    int value_path_len = get_link_list_len(p);
    int other_value_path_len = get_link_list_len(q);
    
    int count = 0;
    if (value_path_len > other_value_path_len) {
        while (count < (value_path_len - other_value_path_len)) {
            p = p -> parent;
            count++;
        }
    }else if(value_path_len < other_value_path_len){
        
        while (count < (other_value_path_len - value_path_len)) {
            q = q -> parent;
            count++;
        }
    }
    
    while (p && q) {
        if (p == q) {
            
            return p;
        }
        
        p = p -> parent;
        q = q -> parent;
    }
    
    return NULL;
    /***
     int vec[] = {100,88,108,77,99,106,125};
     TN* root = NULL;
     create_TN_tree(root, vec, sizeof(vec)/sizeof(int), 0);
     TN* p = lowest_common_ancestor_tree_sub_node_pointer_father(root, 77, 88);
     */
}

int get_link_list_len(TN* root){
    
    int len = 0;
    while (root) {
        
        root = root -> parent;
        len++;
    }
    
    return len;
}

void find_current_value_node(TN* root,TN*& p,int val){
    
    if (!root) {
        return ;
    }
    
    if(root -> val == val){
        p = root;
        return;
    }
    
    if (root -> l) {
        find_current_value_node(root -> l,p, val);
    }
    
    if (root -> r) {
        find_current_value_node(root -> r,p, val);
    }
}

#pragma mark 判断一个二叉树是不是另外一个二叉树的子数
bool is_sub_tree_equal(TN* sub_tree_left,TN* sub_tree_right){
    
    if ((!sub_tree_left && sub_tree_right) || (sub_tree_left && !sub_tree_right)) {
        return false;
    }
    
    if (!sub_tree_left && !sub_tree_right) {
        return true;
    }
    
    if (sub_tree_left -> val != sub_tree_right -> val) {
        return false;
    }
    
    return is_sub_tree_equal(sub_tree_left -> l,sub_tree_right -> l) && is_sub_tree_equal(sub_tree_left -> r,sub_tree_right -> r);
}

void is_sub_tree(TN* target_tree,TN* sub_tree,bool& flag){
    
    if (!sub_tree) {
        flag = true;
        return;
    }
    
    if (!target_tree) {
        
        return;
    }
    
    if ((sub_tree -> val - target_tree -> val <= 0.0000001) && (sub_tree -> val - target_tree -> val >= -0.0000001)) {
        
        flag = is_sub_tree_equal(target_tree,sub_tree);
        NSLog(@"%d,%d",sub_tree -> val,target_tree -> val);
    }
    
    if (target_tree -> l) {
        is_sub_tree(target_tree -> l,sub_tree,flag);
    }
    
    if (target_tree -> r) {
        is_sub_tree(target_tree -> r,sub_tree,flag);
    }
    
    /**
     int vec[] = {100,88,108,77,99,106,125};
     TN* root = NULL;
     create_TN_tree(root, vec, sizeof(vec)/sizeof(int), 0);
     
     int sub_vec[] = {108,106,125};
     TN* sub_root = NULL;
     create_TN_tree(sub_root,sub_vec , sizeof(sub_vec)/sizeof(int), 0);
     
     bool flag = false;
     is_sub_tree(root,sub_root,flag);
     */
}

#pragma mark 栈的压入,弹出序列
bool is_stack_pop_order(int* push,int* pop,int len){
    
    bool ret = false;
    if (push && pop && len > 0) {
        
        stack<int> stack;
        const int* pushNext = push;
        const int* popNext = pop;
        
        while (popNext - pop < len) {
            
            while (stack.empty() || stack.top() != *popNext) {
                
                if (pushNext - push == len) {
                    break;
                }
                stack.push(*pushNext);
                
                pushNext++;
            }
            
            if (stack.top() != *popNext) {
                ret = false;
                break;
            }
            stack.pop();
            popNext++;
        }
        
        if (stack.empty() && popNext - pop == len) {
            ret = true;
        }
    }
    /*
     int push[] = {1,2,3,4,5};
     int pop[] = {4,3,5,1,2};
     bool ret = is_stack_pop_order(push,pop,5);
     */
    
    return ret;
}

#pragma mark 链表逆序相加,并逆序
std::list<int> list_reverse_add(std::list<int> list1,std::list<int> list2){
    
    list<int> ret;
    if (list1.empty() || list2.empty()) {
        return ret;
    }
    
    list1.reverse();
    list2.reverse();
    bool add_bit = false;
    while (!list1.empty() || !list2.empty()) {
        
        int value1 = 0;
        int value2 = 0;
        if (!list1.empty()) {
            
            value1 = list1.front();
        }
        
        if (!list2.empty()) {
            
            value2 = list2.front();
        }
    
        int result = value1 + value2;
        if (add_bit) {
            
            result += 1;
            add_bit = false;
        }
        
        if (result >= 10) {
            
            result = result % 10;
            add_bit = true;
        }
        
        ret.push_back(result);
        
        list1.pop_front();
        list2.pop_front();
        
    }
    
    if (add_bit) {
        ret.push_back(1);
    }
    
    ret.reverse();
    
    return ret;
    /**
     std::list<int> list1;
     
     list1.push_back(5);
     list1.push_back(2);
     list1.push_back(3);
     list1.push_back(4);
     list1.push_back(5);
     list1.push_back(6);
     
     std::list<int> list2;
     
     list2.push_back(5);
     list2.push_back(2);
     list2.push_back(3);
     list2.push_back(4);
     list2.push_back(5);
     list2.push_back(6);
     
     std::list<int> list = list_reverse_add(list1, list2);
     for (std::list<int>::iterator iter = list.begin(); iter != list.end() ; iter++) {
     NSLog(@"begin %d",*iter);
     }
     */
}

#pragma mark 图的深度优先遍历
const static int max_vertex = 100;
typedef struct _graph{
    
    int vertexs;
    int edges;
    char vertex[max_vertex];
    int matrix[max_vertex][max_vertex];
    
}graph;


int get_position(graph* graph,int v){
    
    if (!graph) {
        return -1;
    }
    
    for (int i = 0; i < graph -> vertexs; i++) {
        
        if (graph -> vertex[i] == v) {
            return i;
        }
    }
    return  -1;
    
}

graph* graph_walk(){
  
    graph* graph = new _graph();
    
    graph -> edges = 7;
    graph -> vertexs = 7;
    
    graph -> vertex[0] = 'A';
    graph -> vertex[1] = 'B';
    graph -> vertex[2] = 'C';
    graph -> vertex[3] = 'D';
    graph -> vertex[4] = 'E';
    graph -> vertex[5] = 'F';
    graph -> vertex[6] = 'G';
    
    char edges[][2] = {
        {'A', 'C'},
        {'A', 'D'},
        {'A', 'F'},
        {'B', 'C'},
        {'C', 'D'},
        {'E', 'G'},
        {'F', 'G'}
    };
    
    for (int i = 0; i < graph -> edges; i++) {
        
        int p = get_position(graph, edges[i][0]);
        int q = get_position(graph, edges[i][1]);
        
        graph -> matrix[p][q] = 1;
        graph -> matrix[q][p] = 1;
        
    }
    
    int visited[7];
    memset(visited, 0, sizeof(visited));

    dfs(graph, visited, 0);
    return NULL;
}


int first_vertex(graph* graph,int v){
    
    if (!graph || v >= graph -> vertexs) {
        return -1;
    }
    
    for (int i = 0; i < graph -> vertexs; i++) {
        
        if (graph -> matrix[v][i] == 1) {
            return i;
        }
    }
    return -1;
}

int next_vertex(graph* graph,int v,int next){
    
    if (!graph || (v >= graph -> vertexs) || (next + 1 >= graph -> vertexs)) {
        return -1;
    }
    
    for (int i = next + 1; i < graph -> vertexs; i++) {
        
        if (graph -> matrix[v][i] == 1) {
            return i;
        }
    }
    
    return -1;
}

void dfs(graph* graph,int* visited,int index){
    
    if (!graph || !visited) {
        return;
    }
    
    NSLog(@" %c ",graph -> vertex[index]);
    visited[index] = 1;
    
    int i = first_vertex(graph, index);
    for (; i >= 0; i = next_vertex(graph, index, i)) {
        
        if (!visited[i]) {
            dfs(graph, visited,i);
        }
    }
}

#pragma mark 拓扑排序 -- (针对有向无环图)邻接表实现
#define max_len 100
typedef struct _ENode{
    
    int index;
    struct _ENode* next;
    
}ENode;

typedef struct _LNode{
    
    char data;
    ENode* first_Node;
    
}LNode;

typedef struct _Adjacency_list{
    
    int vertexs;
    int edges;
    LNode lNode[max_len];
    
}Adjacency_list;

int get_adjacency_position(Adjacency_list* graph,char ch){
    
    if (!graph) {
        return -1;
    }
    
    for (int i = 0; i < graph -> vertexs; i++) {
        
        if (graph -> lNode[i].data == ch) {
            return i;
        }
    }
    
    return -1;
}

void toplogical_sort(){
    
    char vertexs[] = {'A','B','C','D','E','F','G','H','J'};
    char edges[][2] = {
        'B','A',
        'B','D',
        'D','E',
        'D','F',
        'A','G',
        'C','G',
        'C','A',
        'H','J',
        'G','H',
    };
    
    Adjacency_list* graph = new Adjacency_list();
    
    graph -> edges = sizeof(edges) / 2;
    graph -> vertexs = sizeof(vertexs);
    
    for (int i = 0; i < graph -> vertexs; i++) {
        
        graph -> lNode[i].data = vertexs[i];
        graph -> lNode[i].first_Node = NULL;
    }
    
    // 创建邻接表
    for (int i = 0; i < graph -> edges; i++) {
        
        int c1 = get_adjacency_position(graph,edges[i][0]);
        int c2 = get_adjacency_position(graph,edges[i][1]);
    
        ENode* node = new ENode();
        node -> index = c2;
        node -> next = NULL;
        if(graph -> lNode[c1].first_Node == NULL){
            
            graph -> lNode[c1].first_Node = node;
            
        }else{
            
            ENode* p = graph -> lNode[c1].first_Node;
            while (p -> next) {
                p = p -> next;
            }
            p -> next = node;
        }
    }
    
    for (int i = 0; i < graph -> vertexs;i++) {
        
        NSLog(@"%c",graph -> lNode[i].data);
        ENode* node = graph -> lNode[i].first_Node;
        while (node) {
            NSLog(@"%d",node -> index);
            node = node -> next;
        }
    }
    
    // 统计每个顶点的入度数
    std::vector<int> vertex_in_degree(graph -> vertexs,0);

    for (int i = 0; i < graph -> vertexs;i++) {
    
        ENode* node = graph -> lNode[i].first_Node;
        while (node) {
            vertex_in_degree[node -> index]++;
            node = node -> next;
        }
    }
    
    std::queue<int> temp_queue;
    std::queue<int> result_queue;
    
    while (result_queue.size() < graph -> vertexs) {
        
        for (int i = 0; i < graph -> vertexs; i++) {
            
            if (vertex_in_degree[i] == 0) {
                temp_queue.push(i);
            }
        }
        
        while (!temp_queue.empty()) {
            
            int index = temp_queue.front();
            temp_queue.pop();
            
            //先找到与之相关的边,并减一
            ENode* node = graph -> lNode[index].first_Node;
            
            vertex_in_degree[index]--;
            while (node) {
                vertex_in_degree[node -> index]--;
                node = node -> next;
            }
            
            result_queue.push(index);
            
        }
    }
    
    //拓扑排序的最终结果
    while (!result_queue.empty()) {
        NSLog(@" %d ",result_queue.front());
        result_queue.pop();
    }
    
  
    //删除节点
    
    //删出图
    delete graph;
    int break_p = 10;
}

#pragma mark 循环队列
template <typename T>
class cycle_queue{
    
private:
    
    unsigned    head_index;
    unsigned    tail_index;
    T*          base;
    unsigned    max_size;

public:
    void init(unsigned size){
        
        base = new T[size];
        head_index = tail_index = 0;
        max_size = size;
    }
    
    bool insert(T element){
        
        if(!base){
            return false;
        }
        
        if((tail_index + 1) % max_size == head_index){
            NSLog(@"queue is full,insert error:%d",element);
            return false;
        }
        
        base[tail_index] = element;
        tail_index++;
        return true;
    }
    
    bool consume_once(T& element){
        
        if(!base){
            return false;
        }
        
        if(tail_index == head_index){
            return false;
        }
        
        element = base[head_index];
        head_index++;
        
        return true;
    }
    /**
     
     cycle_queue<float> queue;
     float element = 0;
     queue.init(10.0);
     queue.insert(0.2);
     queue.insert(3);
     queue.insert(4);
     queue.insert(5);
     queue.consume_once(element);
     NSLog(@"first print %.2f",element);
     queue.insert(6);
     queue.insert(7);
     queue.consume_once(element);
     NSLog(@"second print %.2f",element);
     queue.insert(8);
     queue.insert(9);
     while (queue.consume_once(element)) {
     
     NSLog(@"third print %d",element);
     }
     queue.insert(10);
     queue.insert(11);
     queue.consume_once(element);
     NSLog(@"four print %d",element);
     queue.insert(12);
     queue.insert(13);
     while (queue.consume_once(element)) {
     NSLog(@"fifth print %d",element);
     }
     queue.insert(14);
     queue.insert(15);
     while (queue.consume_once(element)) {
     NSLog(@"sixth print %d",element);
     }
     
     queue.insert(16);
     queue.insert(17);
     while (queue.consume_once(element)) {
     NSLog(@"seven print %d",element);
     }
     */
};

#pragma mark 求 1 + 2 + 3 + 4 ... + n 不用乘除法 if while case等关键字 以及条件判断语境 A?B:A(method1:构造函数)
class add_copy_constructor{
    
public:
    
    add_copy_constructor(){
        n++;
        sum += n;
    }
    
    static void reset(){
        n = 0;
        sum = 0;
    }
    
    static int get_sum(){
        return sum;
    }
    
private:
    static int n;
    static int sum;
    /**
     
     add_copy_constructor::reset();
     add_copy_constructor* add = new add_copy_constructor[10];
     int sum = add_copy_constructor::get_sum();
     */
    
};

int add_copy_constructor::n = 0;
int add_copy_constructor::sum = 0;

#pragma mark 求 1 + 2 + 3 + 4 ... + n 不用乘除法 if while case等关键字 以及条件判断语境 A?B:A(method2:递归 对n两次取反转化为bool值,true,false)
typedef int (*pFun) (int n);

int fun_zero(int n){
    
    return 0;
}

int func_add(int n){
    
    pFun func[2] = {fun_zero,func_add};
    
    return n + func[!!n](n - 1);
}

#pragma mark 求 1 + 2 + 3 + 4 ... + n 不用乘除法 if while case等关键字 以及条件判断语境 A?B:A(method3:利用模板类进行) 不懂?????
template<unsigned int n> struct solution4{
    enum value {N = solution4<n - 1>::N + n};
};

template<> struct solution4<1>{
    enum value {N = 1};
};

#pragma mark 不用加减乘除做加法
int bit_add_operation(int a,int b){
    
    int sum = 0;
    do{
        sum = a ^ b;
        int carry = (a & b) << 1;
        
        a = sum;
        b = carry;
    }while(b != 0);
    
    return sum;
    /**
         int sum = bit_add_operation(100, 105);
     */
}

#pragma mark 构建乘积数组 B[i] = A[0] * A[1] * .... * A[n - 2] * A[n - 1] 时间复杂度 O(n)
void mutiply_n(const vector<int>& A,vector<int>& B){

    int a_len = A.size();
    int b_len = B.size();
    
    if (a_len <= 0) {
        
        return;
    }
    
    if (a_len == b_len) {
        
        B[0] = 1;
        
        for (int i = 1; i < a_len - 1; i++) {
            
            B[i] = B[i - 1] * A[i - 1];
        }
        
        int temp = 1;
        for (int i = a_len - 2; i >= 0; --i) {
            
            temp = temp * A[i + 1];
            B[i] = B[i] * temp;
        }
    }
}


#pragma mark 构建乘积数组 B[i] = A[0] * A[1] * .... * A[n - 2] * A[n - 1] 时间复杂度 O(n2)
void mutiply_n2(const vector<int>& A,vector<int>& B){
    
    int a_len = A.size();
    int b_len = B.size();
    
    if (a_len <= 0) {
        
        return;
    }
    
    if (a_len == b_len) {
        
        for (int i = 0; i < a_len - 1; i++) {
            
            int result = 1;
            for (int j = 0; j < a_len; j++) {
                
                if (i == j) {
                    continue;
                }
                
                result *= A[j];
            }
            
            B[i] = result;
        }

    }
    
    /*
     vector<int> A;
     A.push_back(1);
     A.push_back(2);
     A.push_back(3);
     A.push_back(4);
     A.push_back(5);
     A.push_back(6);
     
     vector<int> B;
     B.push_back(0);
     B.push_back(0);
     B.push_back(0);
     B.push_back(0);
     B.push_back(0);
     B.push_back(0);
     
     mutiply_n(A, B);
     /*
     [0] = 720
     [1] = 360
     [2] = 240
     [3] = 180
     [4] = 144
     [5] = 0
     */
    
    //mutiply_n2(A, B);
    /**
     [0] = 720
     [1] = 360
     [2] = 240
     [3] = 180
     [4] = 144
     [5] = 0
     */
}

typedef struct _list_node{
    
    int value;
    struct _list_node* next;
}list_node;

list_node* list_reverse(list_node* head){
    
    if (head == NULL || head -> next == NULL) {
        return head;
    }
    
    list_node* node = list_reverse(head -> next);
    head -> next -> next = head;
    head -> next = NULL;
    
    return node;
}

list_node* reverse_k_group(list_node* head,int k){
   
    if (head == NULL || k <= 0) {
        return NULL;
    }
    
    return reverse_k_group_core(head,k);
}

list_node* reverse_k_group_core(list_node* head,int k){
    
    list_node* temp = head;
    for (int i = 1; i < k; i++) {
        
        if (temp == NULL) {
            return head;
        }
        temp = temp -> next;
    }
    
    if (temp == NULL) {
        return head;
    }
    
    //断掉每k个节点之间的关系,便于反转
    list_node* next_head = temp -> next;
    temp -> next = NULL;
    
    list_node* new_head = list_reverse(head);

    list_node* k_node = reverse_k_group_core(next_head, k);
    
    head -> next = k_node;
    
    return new_head;

}


#pragma mark 单链表表示十进制整数,求两个整数的和 1234 + 34 = 1268
list_node* list_add(list_node* list_a,list_node* list_b){
    
    if (!list_a) {
        return list_b;
    }
    
    if (!list_b) {
        return list_a;
    }
    
    list_node* list_a_reverse = list_reverse(list_a);
    list_node* list_b_reverse = list_reverse(list_b);
    
    list_node* head = new list_node();
    list_node* temp = head;
    bool carry = false;
    while (list_a_reverse || list_b_reverse) {
        
        int a = 0;
        int b = 0;
        if (list_a_reverse) {
            a = list_a_reverse -> value;
            list_a_reverse = list_a_reverse -> next;
        }
        
        if (list_b_reverse) {
            b = list_b_reverse -> value;
            list_b_reverse = list_b_reverse -> next;
        }
        
        int sum = 0;
        if (carry) {
            sum = a + b + 1;
        }else{
            sum = a + b;
        }
       
        if (sum >= 10) {
            temp -> value = sum % 10;
            carry = true;
        }else{
            temp -> value = sum;
            carry = false;
        }
        
        if (list_a_reverse || list_b_reverse) {
            
            list_node* new_node = new list_node();
            temp -> next = new_node;
            temp = new_node;
            temp -> next = NULL;
        }
    }
    
    if (carry) {
        list_node* new_node = new list_node();
        temp -> next = new_node;
        
        new_node -> value = 1;
        new_node -> next = NULL;
    }
    
    head = list_reverse(head);
    
    return head;
    /**
     list_node* node1 = new list_node();
     node1 -> value = 7;
     
     list_node* node2 = new list_node();
     node2 -> value = 7;
     node1 -> next = node2;
     
     //    list_node* node3 = new list_node();
     //    node3 -> value = 7;
     //    node2 -> next = node3;
     //
     //    list_node* node4 = new list_node();
     //    node4 -> value = 7;
     //    node3 -> next = node4;
     
     node2 -> next = NULL;
     
     list_node* nodeb1 = new list_node();
     nodeb1 -> value = 3;
     
     
     list_node* nodeb2 = new list_node();
     nodeb2 -> value = 4;
     nodeb1 -> next = nodeb2;
     
     nodeb2 -> next = NULL;
     
     list_node* temp = list_add(node1,nodeb1);
     while (temp) {
     NSLog(@"%d",temp -> value);
     temp = temp -> next;
     }
     */
    
}

#pragma mark AVL tree(平衡二叉树)

#define avl_node_len(p) (p == NULL ? 0 : (p) -> height)

typedef struct _avl_node{
    
    int key;
    struct _avl_node* left;
    struct _avl_node* right;
    int height;
    
}avl_node;


//根节点的左子树的左子树还有非空子节点 LL
avl_node* left_left_rotate(avl_node* node){
    
    if (!node) {
        return NULL;
    }
    
    avl_node* k = node -> left;
    
    if (!k) {
        return NULL;
    }
    
    node -> left = k -> right;
    k -> right = node;
    
    node -> height = MAX(avl_node_len(node -> left), avl_node_len(node -> right)) + 1;
    k -> height = MAX(avl_node_len(k -> left), node -> height) + 1;
    
    return k;
}

//根节点右子树的右子树还有非空子节点 RR
avl_node* right_right_rotate(avl_node* node){
    
    if (!node) {
        return NULL;
    }
    
    avl_node* k = node -> right;
    
    if (!k) {
        return NULL;
    }
    
    node -> right = k -> left;
    k -> left = node;
    
    node -> height = MAX(avl_node_len(node -> left), avl_node_len(node -> right)) + 1;
    k -> height = MAX(avl_node_len(k -> right), node -> height) + 1;
    
    return k;
}

//根节点的左子树的右子树还有非空节点LR
avl_node* left_right_rotate(avl_node* node){
    
    if (!node) {
        return NULL;
    }
    
    node -> left = right_right_rotate(node -> left);
    
    return left_left_rotate(node);
}

//根节点的右子树的左子树还有非空节点RL
avl_node* right_left_rotate(avl_node* node){
    
    if (!node) {
        return NULL;
    }
    
    node -> right = left_left_rotate(node -> right);
    
    return right_right_rotate(node);
}

void avl_insert_node(avl_node*& tree,int value){
    
    if (tree == NULL) {
        
        tree = new avl_node();
        tree -> left = NULL;
        tree -> right = NULL;
        tree -> height = 0;
        tree -> key = value;
        
    }else if(tree -> key < value){
        
        avl_insert_node(tree -> right, value);
        
        //(RL or RR)
        if (avl_node_len(tree -> right) - avl_node_len(tree -> left) == 2) {
            
            if (tree -> right -> key < value) {
                
               tree = right_right_rotate(tree);
               
            }else {
                
               tree = right_left_rotate(tree);
            }
        }
        
    }else if (tree -> key > value){
        
        avl_insert_node(tree -> left, value);
        
        // LR ,LL
        if(avl_node_len(tree -> left) - avl_node_len(tree -> right) == 2){
            
            if (tree -> left -> key > value) {
               tree = left_left_rotate(tree);
                
            }else{
               tree = left_right_rotate(tree);
            }
        }
        
    }else if (tree -> key == value){
    
        
    }
    
    tree -> height = MAX(avl_node_len(tree -> left), avl_node_len(tree -> right)) + 1;
}

avl_node* max_avl_node(avl_node* tree){
    
    if (!tree) {
        return NULL;
    }
    
    while (tree -> right) {
        tree = tree -> right;
    }
    
    return tree;
}

avl_node* min_avl_node(avl_node* tree){

    if (!tree) {
        return NULL;
    }
    
    while (tree -> left) {
        tree = tree -> left;
    }
    
    return tree;
}


void avl_delete_node(avl_node*& tree,int value){
    
    if (!tree) {
        return;
    }
    
    if (tree -> key < value) {
        
        avl_delete_node(tree -> right, value);
        if (avl_node_len(tree -> left) - avl_node_len(tree -> right) == 2) {
            //LR,LL
            if (avl_node_len(tree -> left -> right) > avl_node_len(tree -> left -> left)) {
                tree = left_right_rotate(tree);
            }else {
                tree = left_left_rotate(tree);
            }
        }
        
    }else if(tree -> key > value){
        
        avl_delete_node(tree -> left, value);
        if (avl_node_len(tree -> right) - avl_node_len(tree -> left) == 2) {
             //RL RR
            if (avl_node_len(tree -> right -> left) > avl_node_len(tree -> right -> right)) {
                tree = right_left_rotate(tree);
            }else{
                tree = right_right_rotate(tree);
            }
        }
        
    }else{
        
        if (tree -> left && tree -> right) {
            
            if(avl_node_len(tree -> left) > avl_node_len(tree -> right)){
                //左子树找最大节点
                avl_node* max_node = max_avl_node(tree -> left);
                tree -> key = max_node -> key;
                avl_delete_node(tree -> left, max_node ->key);
                
            }else{
                
                //右子树找最小节点
                avl_node* min_node = min_avl_node(tree -> right);
                tree -> key = min_node -> key;
                avl_delete_node(tree -> right, min_node -> key);
                
            }
            
        }else{
            
            avl_node* temp = tree;
            tree = tree -> left ? tree -> left: tree -> right;
            delete temp;
        }
        
    }
}

void walk_avl_tree(avl_node* node){
    
    if (!node) {
        return;
    }
    
    queue<avl_node*> queue;
    queue.push(node);
    while (!queue.empty()) {
        
        avl_node* node = queue.front();
        queue.pop();
        
        NSLog(@"%d",node -> key);
        
        if (node -> left) {
            queue.push(node -> left);
        }
        
        if(node -> right){
            queue.push(node -> right);
        }
    }
}


#pragma mark 红黑树
typedef struct _red_black_node{
    
    unsigned char color;
    int key;
    struct _red_black_node* left;
    struct _red_black_node* right;
    
    
}red_black_node;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值