Several typical test questions

Source: Internet
Author: User

1. Recursive merge of ordered linked lists

2. Search for the nearest common ancestor of two nodes in a binary tree

3. hexadecimal algorithm conversion

4. case-insensitive Conversion

5. Calculate the median of two arrays with the same length

6. Calculate the k Number of the array

7. k Number of medians closest to S

1. Recursive merge of ordered linked lists

Node* mergAction(Node* head1,Node *head2){   Node *p=NULL;   if(head1==NULL&&head2==NULL)       return p;   else if(head1==NULL)       return head2;   else if(head2==NULL)       return head1;   else   {        if(head1->data < head2->data)        {            p = head1;            p->next = mergAction(head1->next,head2);        }        else        {           p = head2;           p->next = mergAction(head1,head2->next);        }        return p;   }}

2. Search for the nearest common ancestor of two nodes in a binary tree

Class node {node * left; node * right; node * parent;};/* searches for the nearest common ancestor of p and q and returns it. */Node * nearestcommonancestor (node * P, node * q );

Node * NearestCommonAncestor(Node * root,Node * p,Node * q){Node * temp;         while(p!=NULL){p=p->parent;temp=q;while(temp!=NULL){if(p==temp->parent)return p;temp=temp->parent;}}}

Solution 2:Algorithm idea: If the left subtree of a node contains a node in p and q, And the right subtree contains another node, the node is the closest common ancestor of p and q.

/* Find the nearest public ancestor of A and B. The root node and the out node are the pointer addresses of the nearest public ancestor */INT findnca (node * root, node * a, node * B, node ** out) {If (root = NULL) {return 0;} If (root = A | root = B) {return 1 ;} int ileft = findnca (root-> left, a, B, out); If (ileft = 2) {return 2;} int iright = findnca (root-> right, a, B, out); If (iright = 2) {return 2;} If (ileft + iright = 2) {* out = root ;} return ileft + iright;} void main () {node * root = ...; node * A = ...; node * B = ...; node * out = NULL; int I = findnca (root, a, B, & out); if (I = 2) {printf ("result pointer is % P ", out) ;}else {printf ("not find Pointer ");}}

3. hexadecimal algorithm conversion

Program to convert a decimal integer into any hexadecimal integer.

A decimal number R and the hexadecimal number X to be converted. The program outputs the converted X-hexadecimal integer.

Algorithm idea: modulo the decimal number R with the hexadecimal number X, that is, the value of R % x is used as the reciprocal first of the X-base integer,

Then, Let R be equal to R/X, and take the value of R % x as the second-to-last digit of the X-base integer ...... and so on.

Until the last r/x = 0.

# Include <iostream> # include <string> using namespace STD;

 

/* Convert an integer to a numeric value, for example, 8-> '8', 12-> 'C' */void numtochar (char & num ){

/* Num is a number between 0 and 9 */If (Num <= 9 & num> = 0) {num + = 48 ;}

 

/* Num is a number between 10 and 15 */else {Switch (Num) {case 10: num = 'a'; Case 11: num = 'B'; Case 12: num = 'C'; Case 13: num = 'D'; Case 14: num = 'E'; Case 15: num = 'F ';}}}

 

/* Base Conversion Function -- r indicates the number of decimal digits to be converted, and X indicates base (1 <x <17) */void decimaltransmit (int r, int X) {string result; // save x hexadecimal number char temp; while (r> 0) {temp = R % x; numtochar (temp); Result + = temp; R = r/X;}/* X-base integer after output conversion */For (INT I = result. size ()-1; I> = 0; I --) cout <result [I]; cout <Endl ;}

 

Int main () {int R, X; cout <"enter a decimal number and the hexadecimal format to be converted (use space as the delimiter ):"; cin> r> X; decimaltransmit (R, x); Return 0 ;}

There is also an mton algorithm, which is very beautiful, but unfortunately only supports 1 ~ Decimal conversion.

Void m2n (int m, char * mnum, int N, char * nnum) {int I = 0; char C, * P = nnum; // This is an area of test, whether to use the least multiplication times. While (* mnum! = '\ 0') I = I * m + * mnum ++-'0'; // return the remainder while (I) {* P ++ = I % N + '0'; I/= n ;}* p -- = '\ 0'; // returns the inverse remainder sequence while (P> nnum) {c = * P; * p -- = * nnum; * nnum ++ = C ;}}

4. case-insensitive Conversion

#define to_uppercase(ch) ((ch) - 'a' + 'A')#define to_lowercase(ch) ((ch) - 'A' + 'a')

I cannot remember it later. Remember to bring special values for testing:

'A'-> 'A' A '-'A' + 'A'

'A'-> 'A' A '-'A' + 'A'

It seems that I have been thinking about this simple answer for a long time in the test room, which shows the poor status.

5. Calculate the median of two arrays with the same length

Median:Set X [0: n-1] and y [0: n-1] as two arrays. Each array contains N sorted numbers. Design an O (logn) time algorithm to find the median of 2n numbers of X and Y.

Core issues: Find the cutting points that divide the big problem into smaller ones with the same problem, and recursively define the relationship between the big problem and the subproblem. Confirm the cutting point: For two arrays, we can select a median from them, called X and Y, and call the left and right boundary of the two arrays Aleft, aright, bleft, and bright. Compare two medians. If the median in array X is greater than the median in array Y and the number of elements in array X is an even number, the array X is split into [Aleft, x + 1], Y is cut to Y [y, bright]. If the number of elements in the array X is not an even number, X is directly cut to X [Aleft, X]. If the median of array X is smaller than the median of array y, the values are the opposite. Recursive relationship: As described above, for the original issue X [Aleft, aright], Y [bleft, bright]. Assume that the subproblem after cutting is X [Aleft, x + 1], Y [y, bright]. The median for solving the X [Aleft, aright], Y [bleft, bright] problems is attributed to solving subproblems X [Aleft, x + 1], Y [y, the median of bright. Recursive end Condition: When the length of the two arrays in the subproblem obtained after cutting is two bits, the entire recursion ends. Input of the actual problem:
The first line is N, which is the number of elements in array X and array y.
Row 2: n of array X, separated by Spaces

Row 3: n of array y, separated by Spaces

Algorithm output:
Two medians separated by Spaces
# Include <stdio. h> # include <stdlib. h> int main () {// two arrays int Len = 0; // obtain the array length scanf ("% d", & Len ); // dynamically allocate an array int * A; int * B; A = (int *) malloc (sizeof (INT) * Len); B = (int *) malloc (sizeof (INT) * Len); // obtain the element of each array for (INT I = 0; I <Len; I ++) {scanf ("% d ", & A [I]) ;}for (Int J = 0; j <Len; j ++) {scanf ("% d", & B [J]);} // The coordinates of the left and right endpoints of the two arrays int Aleft = 0; int aright = len-1; int bleft = 0; int bright = len- 1; // The coordinate between the two arrays int amid = 0; int bmid = 0; // iteration loop while (true) {// printf ("A left is % d right is % d, and B left is % d right is % d. \ n ", Aleft, aright, bleft, bright); // if both arrays have only two elements left, the median must be in the IF (aright-Aleft) = 1 & (bright-bleft) = 1) {// outputs the largest value of printf ("% d ", (A [Aleft]> = B [bleft])? A [Aleft]: B [bleft]); // outputs the smallest value of printf ("% d \ n ", (A [aright] <= B [bright])? A [aright]: B [bright]); // end cycle break;} else {// median amid = (INT) (Aleft + aright) of each array) /2); bmid = (INT) (bleft + bright)/2); // if the value of a is smaller than the value of B, if (a [amid] <B [bmid]) {// if the number of existing columns in B is an even number, add one if (bleft + bright + 1) % 2 = 0) {Aleft = amid; bright = bmid + 1;} else {Aleft = amid; bright = bmid ;}} // if the value of B is smaller than the value of A, else {// if the number of existing columns in A is an even number, the value on the right is plus if (Aleft + aright + 1) % 2 = 0) {aright = amid + 1; bleft = bmid;} else {aright = amid; bleft = bmid ;}}} return 0 ;}


6. Calculate the k Number of the array:

It's too classic. I often ask for questions during interviews. For more information, see Introduction to algorithms.

# Include <cstdlib> # include <iostream>/*** calculate the k-th largest number in an array * Basic Idea: * use the last element x as the axis, the array is divided into two parts: SA and Sb. The element in SA is greater than or equal to X, and the element in Sb is less than X. There are two cases: * 1. if the number of elements in SA is smaller than K, the K-| sa | element in Sb is the k-th number. * 2. if the number of elements in SA is greater than or equal to K, the maximum K number in SA is returned. * The time complexity is approximately O (n) */using namespace STD; void Exchange (Int & A, Int & B) {int temp; temp = A; A = B; B = temp;} // The Partition Function int partition (int * a, int L, int R) {int I = IL-1, j = L; int x = A [R]; int temp; For (j = L; j <r; j ++) {if (a [J]> = X) // forward the number larger than X to {Exchange (A [J], a [I + 1]); I ++ ;}} Exchange (A [R], A [I + 1]); return I + 1;} int k_element (int * a, int L, int R, int K) {If (L> = r) return a [l]; int q = partition (A, L, R); If (q = k-1) return a [Q]; else if (q> = K) return k_element (A, L, Q-1, k); // The number of elements in SA is greater than or equal to k else return k_element (A, q + 1, R, k-(q + 1); // The number of elements in SA is less than k} int main (INT argc, char * argv []) {int A [100]; int length; cin> length; For (INT I = 0; I <length; I ++) CIN> A [I]; cout <k_element (A, 0, length-1, 4) <Endl; System ("pause"); Return exit_success ;}

7. k Number of medians closest to S

Problem description:
Given a set of S and a positive integer k <= n composed of N complementary numbers, we try to design an O (n) time algorithm to find the k Number of the medians closest to S in S.
Algorithm analysis:
First, use the select algorithm to obtain the median of the array, and then subtract the median from each number in the set, and then obtain ABS (). Finally, in the set obtained in step 2, take the number of K small, and then take the number of K-1 smaller than the K small number, their original number, is the number of K required. PS: this algorithm is flawed and requires that no duplicates exist in the absolute value array; otherwise, it cannot be linear.

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.