15 basic algorithmic questions with very high frequency (complete code included)

Source: Internet
Author: User
Tags int size

  1. Merge sort to combine two sorted arrays into an array, in which an array can accommodate all the elements of two arrays

    In general, merge two arrays that are already ordered. The first one is to open a third array of the next two arrays that can be saved, but the topic has already been said. One of the arrays can be saved, obviously it should not waste space.
    In the past, the data had to be in the front of a large array, so it was obviously not a good idea to move the elements of a large array back one at a time, so we moved forward from behind.

     #include <iostream> #include <cstdlib>using namespace Std;int cc[10];int tt[    5];void init () {Srand ((unsigned) time (NULL));    int num = rand ()% 5;        for (int i = 0; i < 5; i++) {cc[i] = num;    num + = rand ()% 10 + 1;    num = rand ()% 5;        for (int i = 0; i < 5; i++) {tt[i] = num;    num + = rand ()% 10 + 1;    }}void merge () {int i = 4, j = 4, idx = 9;        while (i>=0 && j>=0) {if (Cc[i] > Tt[j]) cc[idx--] = cc[i--];    else cc[idx--] = tt[j--];    } while (i>=0) cc[idx--] = cc[i--]; while (j>=0) cc[idx--] = tt[j--];}    int main () {init ();    for (int i = 0; i < 5; i++) printf ("%d", cc[i]);    Putchar (10);    for (int i = 0; i < 5; i++) printf ("%d", tt[i]);    Putchar (10);    Merge ();    for (int i = 0; i < i++) printf ("%d", cc[i]);    Putchar (10);    GetChar (); return 0;} 
  2. Merge two sorted single-linked lists

    You cannot create a third linked list and merge them in two ways

    #include <iostream>using namespace std;struct node{int data; node *next;};    void CreateNode (node *head)//create ordered single-linked list with head node {node *s = head;    int val = rand ()% 5 + 1;        for (int i = 0; i < 5; i++) {val + = rand ()% 5 + 1;        Node *t = new node;        T->data = val;        T->next = NULL;    s = s->next = t;    }}void Printnode (node *head) {node *s = head;    while (s = s->next) printf ("%d", s->data); Putchar (10);}    node* merge_1 (node *head1, node *head2)//Sequential Scan {node *i = head1->next;    Node *j = head2->next;    Node *CC = new node;    Node *s = CC;            while (I && j) {if (I->data < j->data) {s = S->next = i;        i = i->next;            } else {s = S->next = J;        j = j->next;    }} if (i) S->next = i;    else S->next = j; return cc;} node* merge_2 (node *head1, node *head2)//recursive {if (hEad1 = = NULL) return head2;    if (head2 = = NULL) return head1;    Node *cc = NULL;        if (Head1->data < head2->data) {cc = HEAD1;    Cc->next = merge_2 (Head1->next, head2);        } else {cc = head2;    Cc->next = merge_2 (Head1, Head2->next); } return cc;}        int main () {srand (unsigned) time (NULL));    Node *linklist1 = new node, *linklist2 = new node;    CreateNode (LINKLIST1);    CreateNode (LINKLIST2);    Printnode (LINKLIST1);    Printnode (LINKLIST2);    LinkList1 = Merge_1 (LinkList1, LinkList2);    Linklist1->next = merge_2 (Linklist1->next, Linklist2->next);   Printnode (LINKLIST1);    The merged linked list exists in 1 getchar (); return 0;}
  3. print a single list in reverse order
     #include <iostream>using namespace std;struct node{int data; node *next;};    void CreateNode (node *&head)//Create an ordered single-linked list without a lead node {head = new node;    Head->data = rand ()% 5 + 1;    Node *s = head, *t = NULL;        for (int i = 0; i < 5; i++) {t = new node;        T->data = S->data + rand ()% 5 + 1;    s = s->next = t; } S->next = NULL;}    void Printnode (node *head) {node *s = head;        while (s! = NULL) {printf ("%d", s->data);    s = s->next; } putchar (10);}    void Printnode_reverse (node *head) {if (Head->next! = NULL) printnode_reverse (Head->next); printf ("%d", Head->data);}        int main () {srand (unsigned) time (NULL));    Node *linklist;    CreateNode (linklist);    Printnode (linklist);    Printnode_reverse (linklist);    Putchar (10);    GetChar (); return 0;} 
  4. A pointer to the head of a single-linked list and a specified node. Delete the node at O (1) time

    See blog: How to delete a single-linked list node in O (1) time

  5. Find the countdown k node of the list

    Set two pointers. A first step forward, K steps. Then the two pointers move synchronously, and when the first pointer goes to the end, the back pointer is in the penultimate position.

    #include <iostream>using namespace std;struct node{int data; node *next;};    void CreateNode (node *&head)//Create an ordered single-linked list without a lead node {head = new node;    Head->data = rand ()% 5 + 1;    Node *s = head, *t = NULL;        for (int i = 0; i < i++) {t = new node;        T->data = S->data + rand ()% 5 + 1;    s = s->next = t; } S->next = NULL;}    void Printnode (node *head) {node *s = head;        while (s! = NULL) {printf ("%d", s->data);    s = s->next; } putchar (10);}    void Find (node *head, int num) {node *s = head, *t = head;    for (int i = 0; i < num; i++) T = t->next;        while (t) {s = s->next;    t = t->next; } printf ("Place:%dth value:%d\n", num, s->data);}        int main () {srand (unsigned) time (NULL));    Node *linklist;    CreateNode (linklist);    Printnode (linklist);    Find (Linklist, 5);    Find (Linklist, 3);    Putchar (10);    GetChar (); return 0;}
  6. Reversing a single linked list

    Using both recursive and non-recursive methods, it is important to check that the reverse function does not go wrong when the list has only a single node.

    #include <iostream>using namespace std;struct node{int data; node *next;};    void CreateNode (node *&head)//Create an ordered single-linked list without a lead node {head = new node;    Head->data = rand ()% 5 + 1;    Node *s = head, *t = NULL;        for (int i = 0; i < i++) {t = new node;        T->data = S->data + rand ()% 5 + 1;    s = s->next = t; } S->next = NULL;}    void Printnode (node *head) {node *s = head;        while (s! = NULL) {printf ("%d", s->data);    s = s->next; } putchar (10);}    node* reverse_1 (node *head)//non-recursive {node *s = head, *t = head->next;    S->next = NULL;        while (t! = NULL) {Node *r = t->next;        T->next = s;        s = t;    t = r; } return s;}    void reverse_2 (node *front, node *n, node *&head)//recursive {front->next = NULL;    if (n! = NULL) head = n;    if (n! = null && N->next! = null) reverse_2 (n, N->next, head); if (n! = NULL) N->next = Front;}        int main () {srand (unsigned) time (NULL));    Node *linklist;    CreateNode (linklist);    Printnode (linklist);    linklist = Reverse_1 (linklist);    Reverse_2 (linklist, Linklist->next, *&linklist);    Printnode (linklist);    Putchar (10);    GetChar (); return 0;}

  7. Implement a queue with two stacks

    See blog: Implementing a queue with two stacks

  8. Two-point Search
    #include <iostream>using namespace std;void binarysearch (int cc[], int num, int key)//array, number of arrays, unknown origin number {    int i = 0 , j = num;    int cnt = 0, mid = 0;    while (I < j)    {        cnt++;        Mid = (i + j) >> 1;        if (cc[mid] = = key)        {            printf ("%d%s, index:%d\n", CNT, cnt==1?)

    "Time": "Times", mid); return; } else if (Cc[mid] < key) i = mid; else j = mid; }} int main () { int cc[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, ten}; BinarySearch (CC, ten, 3); GetChar (); return 0;}

  9. High-speed sequencing

    Two quick rows that are slightly different (the number of incoming parameters is not the same)

    #include <iostream>using namespace Std;int cc[10];void init () {Srand ((unsigned) time (NULL));        for (int i = 0; i < ten; i++) {int idx = rand ()%10;        while (Cc[idx]) idx = rand ()%10;    CC[IDX] = i+1;    }}void Show () {for (int i = 0; i <; i++) printf ("%d", cc[i]); Putchar (10);}    void quicksort_1 (int cc[], int num) {int s = 0, t = num-1;    int base = Cc[0];    if (Num <= 1) return;        while (S < T) {while (T > S && cc[t] >= base) t--;        Cc[s] = cc[t];        while (S < T && Cc[s] <= base) s++;    CC[T] = Cc[s];    } Cc[s] = base;    QuickSort (cc, s); QuickSort (cc+s+1, num-s-1);}    void quicksort_2 (int cc[], int l, int r) {if (L >= R) return;    int s = l, t = r;    int base = Cc[l];        while (S < T) {while (T > S && cc[t] >= base) t--;        Cc[s] = cc[t]; while (S < T && Cc[s] <= base) s++;    CC[T] = Cc[s];    } Cc[s] = base;    Quicksort_2 (CC, L, s-1); Quicksort_2 (CC, s+1, r);}    int main () {init ();    Show ();    Quicksort_1 (CC, sizeof (CC)/sizeof (int));    Quicksort_2 (cc, 0, sizeof (CC)/sizeof (int)-1);    Show ();    GetChar (); return 0;}

  10. Gets the number in the binary of an int type

    Not clear the meaning of this topic, we will understand two small questions:
    (1) The number of bits of an int type, such as the number of 6->110->3 digits
    (2) The number of ' 1 ' in the binary of the int type number

    #include <iostream>using namespace Std;int main () {    int num;    while (~SCANF ("%d", &num))    {        int bits = 0, cnt = 0;        int val = num;        while (Val)        {            if (Val & 1)                cnt++;            bits++;            val>>=1;        }        printf ("%d have%d bit and%d ' 1 ' in binary\n", num, bits, CNT);    }    return 0;}
  11. Enter an array to implement a function. Keep all odd numbers in front of even numbers
    #include <iostream>using namespace Std;int cc[10];void init () {    Srand ((unsigned) time (NULL));     for (int i = 0; i < ten; i++)     {        int idx = Rand ()%10;        while (Cc[idx])              idx = rand ()%10;        cc[idx] = i+1;    }}void Show () {    for (int i = 0; i < i++)         printf ("%d", CC [i]);     Putchar (10);} void Sort (int cc[], int size) {    int s = 0, t = size-1;    while (S < T)   &nbsp ; {        while (S < T && (cc[s]&1))              s++;        while (T > S &&!) ( cc[t]&1)) &NBSP;&NBSP;&NBsp;         t--;        Cc[s] ^= cc[t];         Cc[t] ^= cc[s];        cc[s] ^= cc[t];    }}int Main () {    init ();    Show ();    Sort (CC, sizeof (CC)/sizeof (int));    Show ();    GetChar ();    return 0;}
  12. Infer whether a string is still a substring of a string classic problem, with the KMP algorithm.
    #include <iostream>using namespace Std;char t[1000];char p[100];int f[100];int cnt = 0;void KMP ()  // The required number of parameters is char t[] long string, char p[] pattern string. {    int n = strlen (t);    int m = strlen (p);    The mismatch edge of the computed pattern string    f[0] = f[1] = 0;    for (int i = 1; i < m; i + +)    {        int j = f[i];        while (J && p[i]! = p[j]) j = f[j];        F[I+1] = p[i] = = p[j]?j+1:0;    }    int j = 0;    for (int i = 0; i < n; i + +)    {while        (J && t[i]! = p[j]) j = f[j];        if (p[j] = = T[i]) j + +;        if (j = = m)    //Match succeeded            CNT + +;    }} int main () {    cnt = 0;    Gets (t);    Gets (p);    KMP ();    if (CNT >= 1)        printf ("match!\n");    else        printf ("Not match!\n");    GetChar ();    return 0;}
  13. To put a number in an int array into a string, the number that represents the smallest key is to order the int array, the CMP code should be sorted: Assuming that two numbers are A and B, then the size of the AB and BA, such as 12, 15. It's going to be 1215 and 1512 size. Therefore, in order to facilitate the transfer of INT first to char type, so that the comparison of the direct strcat is very convenient.

    #include <iostream>using namespace std;void createarray (int *cc, int num) {    srand ((unsigned int) time (NULL)); c1/>for (int i = 0; i < num; i++)        cc[i] = rand ()% 50;} int cmp (const void *a, const void *b) {    char *s1 = new CHAR[10];    Char *s2 = new CHAR[10];    strcpy (S1, * (char**) a);    strcat (S1, * (char**) b);    strcpy (S2, * (char**) b);    strcat (S2, * (char**) a);    Return strcmp (S1, S2);} void converttominstring (int *cc, int len) {    char** str = (char**) new Int[len];    for (int i = 0; i < len; i++)    {        Str[i] = new CHAR[5];        sprintf (Str[i], "%d", Cc[i]);    }    Qsort (str, Len, sizeof (char*), CMP);    for (int i = 0; i < len; i++)        printf ("%s", Str[i]);    Putchar (10);} int main () {    int cc[5];    Createarray (CC, 5);    Converttominstring (CC, 5);    GetChar ();    return 0;}

  14. Enter a binary tree. Output its image (the swap location of the left and right child nodes of each node)

    watermark/2/text/ahr0cdovl2jsb2cuy3nkbi5uzxqvagfjdhjvea==/font/5a6l5l2t/fontsize/400/fill/i0jbqkfcma==/ The
    uses both recursive and non-recursive methods of Dissolve/70/gravity/southeast.

    #include <iostream> #include <queue>using namespace std;struct node{    int val;     node *left;    node *right;}; void Insert (node *&root, int data) {    if (root = = NULL)     {         root = new node;        Root->val = data;   & nbsp;    Root->left = Root->right = null;        return;    }    if (Root->val > Data)         Insert ( Root->left, data);    else        Insert (root->right, data );}  node* build () {    node *root = null;    Insert (root, ten);    for (int i = 8; I <= 12; i++)     {        if (i = = ten) continue;         Insert (root, i);   }    return root;} void ShowTree (node *root) {    if (root = NULL) return;    printf ("%d", root->val); nbsp;   ShowTree (root->left);    showTree (root->right);} void mirror_1 (node *&root)    //Recursive method {    if (root = NULL) return;    Node *t = root->left;    Root->left = root->right;    Root->right = t; & nbsp;  mirror_1 (root->left);    mirror_1 (root->right);} void mirror_2 (node *&root)     //Non-recursive method {    queue<node*> q;     if (root = NULL)         q.push (Root);    while (!q.empty ())     {        Node *n = Q.front ();         Q.pop (&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NB);sp;  node *t = n->left;        N->left = n->right;         n->right = t;        if (n->left! = NULL)              Q.push (n->left);         if (n->right! = NULL)             q.push (N- >right);   }}int main () {    node *root = Build ();    showTree (root); Putchar (;   ) mirror_1 (root);    showTree (root);p Utchar;    Mirror_2 (Root);    showTree (Root);p Utchar ();        GetChar ();     return 0;}
  15. Enter two linked lists to find their first public node that is, the two linked lists are shaped like "Y".
    I think of two ways:
    ① Two lists are enumerated first, and the lengths of the two linked lists are calculated, if N and M. If the long chain is the length of N, that is n>=m, let the long chain go first n-m step. Short-chain pointers do not go first, so that the two pointers to the end of the same distance, and then two pointers on one side of the synchronization to compare, when two pointers, the current node is the first public node.

    Complexity of Time: O (n+m)
    ② set a map or other key-value pair (hash table), and then the first linked list goes one step. Indexing is based on its address or primary key, and the second list goes one step. Index based on its address or primary key. two lists are searched for indexes when they are traversed. When the discovery has been recorded, then the current node is the first public node. If the length of the two lists before the intersection is respectively N and M, then the spatial complexity is O (Max (n, M) * *). Its time complexity is O (Max (n, M) * 2).
    In contrast I think ② is much better, after all, time is much more important than space. So the following I gave the ② code, with the address as an index. In fact, I think how to create such a cross-linked list and how to store the pointer address can also be used as a topic ha.

    #include <iostream> #include <map>using namespace std;struct node{int val; node *next;};    node* Buildfirtree ()//The first list has 20 nodes {node *root = new node;    Root->val = 1;    Node *s = root, *t = root;        for (int i = 2; I <=; i++) {t = new node;        T->val = i;    s = s->next = t;    } s->next = NULL; return root;}    node* buildsectree (node *firnode)//The second list creates 5 nodes and then receives the 8th node of the first linked list {node *root = new node;    Root->val = 11;    Node *s = root, *t = root;        for (int i = 2; I <= 5; i++) {t = new node;        T->val = ten + i;    s = s->next = t;    } node *k = Firnode;    for (int i = 0; i < 7; i++) K = k->next;    S->next = k; return root;}    void disp (node *root) {node *t = root;        while (t) {printf ("%d", t->val);    t = t->next; } putchar (10);}    Node *getfirstcommonnode (node *fir, node *sec) {map<long, bool> MP;    Mp.clear (); while (Fir &AMP;&Amp        SEC) {if (mp[(long) fir] = = true) return fir;        mp[(long) fir] = true;        FIR = fir->next;        if (mp[(long) sec] = = true) return sec;        mp[(long) sec] = true;    SEC = sec->next; } return NULL;    int main () {node *fir = Buildfirtree ();    printf ("First linklist:");d ISP (FIR);    Node *sec = Buildsectree (FIR);    printf ("Second linklist:");d ISP (sec);    Node *common = Getfirstcommonnode (fir, sec);    if (Common! = NULL) printf ("Common node is:%d\n", common->val);    else printf ("There is no common node\n");    GetChar (); return 0;}

15 basic algorithmic questions with very high frequency (complete code included)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.