Array is the most basic data structure, about the array of face questions are not uncommon, this article lists some common face questions, for reference only, if you have a better topic or ideas, welcome message discussion. There are currently 18 topics, if there are good topics, update at any time.
- Array summation
- To find the maximum and minimum values of an array
- To find the maximum and secondary values of an array
- Find elements in an array that have more than half occurrences
- Find the shortest distance of elements in an array
- Find common elements of two ordered arrays
- Find common elements of three arrays
- Find the unique repeating element in the array
- Find the elements that appear odd number of times
- Satisfies the given number pairs in the array
- Maximum sub-segments and
- Maximum sub-segment product
- Array Loop shift
- Reverse string
- Combinatorial issues
- Merging two arrays
- Reflow problem
- Find the element with the smallest absolute value
Array summation
Given an integer array of n elements, A, the and of all elements in a. You might think it's simple, yes, it's simple, but why do you have to say that for two reasons, first, the problem requires recursion, with just one line of code. Second, this is the first time in my life interview encountered the problem, the meaning of special.
Analysis
To put it simply, two things
1. If the number of array elements is 0, then the and is 0.
2. If the number of elements in the array is n, then the sum of the first n-1 elements is first obtained, plus a[n-1] can
Code
Array sum int sum (int*a, int n) { return n ==0?0:sum (A, n-1) + a[n-1];}
To find the maximum and minimum values of an array
Given an integer array a containing n elements, find the maximum and minimum values
Analysis
The general practice is to traverse once, to find the maximum and minimum values, but what I want to say here is the division of the method (Divide and Couquer), the array into the left and right parts, first to find out the largest and smallest part of the second half, and then find the maximum and minimum value of the second part, Then the overall maximum and minimum values are combined. This is a recursive process, and for the left and right parts of the division, repeat the process until there is only one element or two elements left in the dividing range.
Code
Find the maximum and minimum values of the array, return values in MaxValue and minvaluevoid maxandmin (int *a, int l, int r, int& maxValue, int& minValue) { if (L = = r)//L and R only one element { maxValue = a[l]; MinValue = A[l]; return; } if (l + 1 = = r)//L and R only two elements { if (A[l] >= a[r]) { maxValue = a[l]; MinValue = A[r]; } else { maxValue = a[r]; MinValue = A[l]; } return; } int m = (L + r)/2; Midpoint int lmax;//left partial maximum int lmin;//Left half min. maxandmin (A, L, M, Lmax, lmin);//recursive calculation left half int rm AX; Right partial maximum int rmin;//Right half min maxandmin (A, M + 1, R, Rmax, rmin);//recursive calculation right half maxValue = max (Lmax, Rmax ) ; The total maximum value minValue = min (lmin, rmin);//total Minimum value}
To find the maximum and secondary values of an array
Given an integer array containing n elements, the maximum and secondary values are calculated
Analysis
The thought and the previous question are similar, the same is the division and the method, the first to find the left maximum value Leftmax and the second large value leftsecond, and then find the right maximum value Rightmax and the second large rightsecond, and then merge, how to merge it? Sub-case considerations
1 if Leftmax > Rightmax, then you can be sure Leftmax is the maximum value, but the second large value is not necessarily rightmax, but certainly not rightsecond, just leftsecond and Rightmax to do a comparison.
2 if Rightmax > Leftmax, then you can be sure Rightmax is the maximum value, but the second largest value is not necessarily leftmax, but certainly not leftsecond, so just Leftmax and Rightsecond to do a comparison.
Attention
This method cannot handle the maximum number of elements in a situation, such as 3,5,7,7 will return 7,7 instead of 7, 5. Thank the Netizen who pointed out from scratch.
Code
Find the maximum and secondary values of the array, a is the array to be looked up, left and right is the lookup interval, max and second deposit result void maxandmin (int a[], int left, int right, int&max, int &second) { if (left = = right) { max = A[left]; Second = int_min; } ElseIf (left +1== right) { max = A[left] > a[right]? a[left]: A[right]; Second = A[left] < A[right]? A[left]: a[right]; } else { int mid = left + (right-left)/2; int Leftmax; int Leftsecond; Maxandmin (A, left, Mid, Leftmax, Leftsecond); int Rightmax; int Rightsecond; Maxandmin (A, mid +1, right, Rightmax, rightsecond); if (Leftmax > Rightmax) { max = Leftmax; Second = leftsecond > Rightmax? Leftsecond:rightmax; } else { max = Rightmax; Second = Leftmax < Rightsecond? Rightsecond:leftmax;}}}
Find elements in an array that have more than half occurrences
Given an n integer element of array A, which has an element that occurs more than N/2, this element is evaluated. is said to be a problem of Baidu
Analysis
Sets a counter for the current value and the current value, initializes the current value to the first element of the array, the counter value is 1, and then iterates through the entire array starting from the second element, for each value traversed to a[i]
1 if a[i]==currentvalue, the counter value plus 1
2 if a[i]! = CurrentValue, the counter value is reduced by 1, if the counter value is less than 0, the current value is updated to A[i], and the counter value is reset to 1
Code
//find elements with more than half occurrences in an arrayintFind (intAintN) {intCurvalue = a[0] ;intCount =1; for(inti =1; I < n; ++i) {if(A[i] = = Curvalue) count++;Else{count--;if(Count <0) {curvalue = A[i]; Count =1; } } }returnCurvalue;}
Another method is to sort the array first, then take the middle element, because if an element is more than half the number, then the element must occupy the middle of the array after sorting.
Find the shortest distance of elements in an array
Given an integer array of n elements, find the two elements x and y in the array to minimize the ABS (x-y) value
Analysis
Sort the array first, then iterate once.
Code
int compare (const void* A, const void* b) { return * (int*) A-* (int*) b;} Find the shortest distance of elements in an array void Minimumdistance (int* a, int n) { //Sort qsort (A, n, sizeof (int), compare); int i; Index of number 1 int J;//Index of number 2 int mindistance = Numeric_limits<int>::max (); for (int k = 0; k < n-1; ++k) { if (a[k + 1]-a[k] < mindistance) { mindistance = a[k + 1]-a[k ] ; i = a[k]; j = a[k + 1]; } } cout << "Minimum distance is:" << mindistance << Endl; cout << "i =" << i << "j =" << J << Endl;}
Find common elements of two ordered arrays
Given two ordered (non-descending) integer arrays A and B with n elements, find their common elements, such as
A = 0, 1, 2, 3, 4
b = 1, 3, 5, 7, 9
Output 1, 3
Analysis
Take full advantage of the order of the array of properties, with two pointers I and J respectively to A and B, compare A[i] and b[j], according to the comparison of the results of moving pointers, there are three cases
1. A[i] < B[j], then I add 1, continue to compare
2. a[i] = = B[j], then I and J both add 1, continue to compare
3. A[i] < B[j], then J plus 1, continue to compare
Repeat the process until I or J reaches the end of the array.
Code
Find out two common elements of an array void Findcommon (int* A, int* b, int n) { int i = 0; int j = 0; while (I < n && J < N) { if (A[i] < b[j]) ++i; else if (a[i] = = B[j]) { cout << a[i] << Endl; ++i; ++j; } else//A[i] > b[j] ++j; }}
There are other solutions to this problem, such as any of the elements in a, binary search in B, because there are n elements in a, and binary search in B requires logn. So the time complexity of finding all the same elements is O (Nlogn).
In addition, the above method, as long as B order, a whether the order does not matter, because we just do binary Search in B. If a is also ordered, then using the above method is a bit slower, because if an element in a in B position is K, then a in the next element in B must be located on the right side of K, so this time the search space can be based on the last search results narrowed, rather than still in the entire B search. That is, if both A and B are ordered, the code can make the following changes, recording the position of the elements in B at the time of the last search, as the starting point for the next search.
Find common elements of three arrays
Given three integer arrays of n elements, a, B, and C, the smallest common element is asked.
Analysis
If three arrays are ordered, you can set three pointers to the head of three arrays and then move the pointer by comparing the values of the three pointers to find the common element.
Code
Common elements of three arrays-find only the smallest void findcommonelements (int a[], int b[], int c[], int x, int y, int z) {for (int i = 0, j = 0, k = 0 ; I < x && J < y && K < Z;) { if (A[i] < b[j]) { i++; } else//a[i] >= B[j] { if (B[j] < c[k]) { j + +; } else//B[J] >= C[k] { if (C[k] < A[i]) { k++; } else//c[k] >= A[i] { cout << c[k] << Endl; return ; }}} cout << "Not found!" << Endl;}
If the three arrays are unordered, you can sort a, B, and then do a binary search for any of the elements in C in B and C.
Code
Find common elements of three arrays//O (NLOGN) int uniquecommonitem (int *a, int *b, int *c, int n) { //Sort array a qsort (A, n, sizeof (i NT), compare); Nlogn //Sort array B qsort (b, n, sizeof (int), compare);//Nlogn //For each element in array C, do a bin ARY Search in A and b//This is up to a complexity of N*2*LOGN for (int i = 0; i < N; i++) { if (Binary Search (A, n, C[i]) && BinarySearch (b, N, C[i])) return c[i]; } return-1; Not found}
You can also sort a, and then do a binary search for any of the elements in B and C, but this is problematic.
Code
Find three arrays unique common elements//O (NLOGN) int UniqueCommonItem1 (int *a, int *b, int *c, int n) { //Sort array a qsort (A, N, Sizeo f (int), compare); Nlogn //Space for time bool *BB = new Bool[n]; memset (BB, 0, N); BOOL *BC = new Bool[n]; memset (BB, 0, N); For per element in B, does a BS in a and mark all the common element for (int i = 0; i < n; i++)//Nlogn {
if (BinarySearch (A, n, B[i])) bb[i] = true; } For per element in C, does a BS only if b[i] are true for (int i = 0; i < n; i++)//Nlogn { if (B[i] &A mp;& BinarySearch (A, n, C[i])) return c[i]; } return-1; Not found}
The sorting and binary search codes are as follows
Determine whether a contains value kbool binarysearch (int *a, int n, int k) { int left = 0; int right = n-1; while (left <= right) { int mid = (left + right); if (A[mid] < K) Left = mid + 1; if (a[mid] = = k) return true; else right = mid-1; } return false;} Compare function for Qsortint Compare (const void* A, const void* b) { return * (int*) A-* (int*) b;}
A little summary, for the problem of searching in the array, can be divided into the following two cases of processing
1. If the given array is ordered, you should first think of binary Search, the required O (LOGN)
2. If the given array is unordered, you should first think of sorting the arrays, many sorting algorithms can sort the array in O (Nlogn) time, and then use the binary search, the total time complexity is still O (Nlogn).
If we can do the above two points, most of the problem of searching for arrays can be solved.
Find the unique repeating element in the array
Given an array of 1001 elements, where an integer within 1-1000 is stored, and only one integer is duplicated, find out the number
Analysis
The whole array is calculated, minus 1-1000 and
Code
Slightly
Find the elements that appear odd number of times
Given an integer array of n elements, a, where only one element appears in odd number of times to find this element. This problem is actually a variant, the original problem is to find the only one occurrence of the element in the array, the following method can be resolved at the same time the two mentioned. So the topic is in this broad sense.
Analysis
Because for any number k, there is k ^ k = 0,k ^ 0 = k, so that all elements of a are different or, then the number of an even-numbered element will become 0, leaving only the number of odd elements.
Code
int Findelementwithoddcount (int*a, int n) { int r = a[0]; for (int i =1; i < n; ++i) { R ^= a[i]; } return r;}
Satisfies the given number pairs in the array
Given two ordered integer arrays A and B, each with n elements, for a given number of pairs in the two array, that is, element I and B in a elements j, satisfies i + j = d (d known)
Analysis
Two pointers I and J point to the end of the array respectively, and then traverse from both ends to the middle, until two pointers cross.
Code
Find the number pair void Fixedsum (int* A, int* b, int n, int d) that satisfies the given and, {for (int i = 0, j = n-1; I < n && J >= 0)
{ if (A[i] + b[j] < D) ++i; else if (A[i] + b[j] = = d) { cout << a[i] << "," << B[j] << Endl; ++i; --j; } else//a[i] + b[j] > D --j; }}
Maximum sub-segments and
Given an integer array A, the sum of the largest contiguous sub-segments is calculated, if and to a negative number, 0, such as 1, 2, 5, 6, 8 output 6 + 8 = 14
Analysis
Programming Zhu Ji Nanxiong on the classic topic, not much to say.
Code
The maximum and int Sum of the Subarray (int* A, int n) { int cursum = 0; int maxsum = 0; for (int i = 0; i < n; i++) { if (cursum + A[i] < 0) cursum = 0; else { Cursum + = A[i]; Maxsum = Max (maxsum, cursum); } } return maxsum;}
Maximum sub-segment product
Given an integer array A, the product of the maximal contiguous sub-segment is obtained, such as 1, 2, 8, 12, 7 output 12 * 7 = 84
Analysis
As with the maximum sub-segment and similar, pay attention to handling negative cases
Code
The maximum product of a subarray of int maxproduct (int *a, int n) { int maxproduct = 1;//MAX positive product at current position int MINP roduct = 1; Min Negative product at current position int r = 1;//result, max multiplication totally for (int i = 0; I < ; N i++) { if (A[i] > 0) { maxproduct *= a[i]; minproduct = min (minproduct * a[i], 1); } else if (a[i] = = 0) { maxproduct = 1; minproduct = 1; } else//A[i] < 0 { int temp = maxproduct; Maxproduct = Max (Minproduct * a[i], 1); minproduct = temp * A[i]; } r = Max (r, maxproduct); } return r;}
Array Loop shift
Moving an array of n elements to the right to move the K-bit, requiring a time complexity of O (n), and using only two additional variables, is a problem seen in the beauty of Microsoft's programming
Analysis
For example, array 1 2 3 4 loop Right shift 1 bits will become 4 1 2 3, observe that the order of 1 2 3 has not changed before and after the shift, but only with the position of 4 exchange, so the equivalent of 1 2 3 4 first divided into two parts
1 2 3 | 4, then 1 2 3 in reverse order, and then 4 order to get 3 2 1 4, and finally the overall reverse to get 4 1 2 3
Code
Reverse the element between start and end in buffer, void Reverse (int buffer[], int start, int end) {while (Start < end) { int te MP = buffer[start]; buffer[start++] = buffer[end]; buffer[end--] = temp; }} The array containing n elements is shifted to the right of K-bit void Shift (int buffer[], int n, int k) { k%= n; Reverse (buffer, 0, n-k-1); Reverse (buffer, n-k, n-1); Reverse (buffer, 0, n-1);}
A little extension, if you allow the allocation of additional arrays, then define a new array, and then the shifted elements are stored directly, you can also use the queue, the moving elements out of the pair, and then inserted into the tail of the team.
Reverse string
Given a character array a containing n elements, reverse it in place.
Analysis
Maybe you think it's not about arrays, it's about strings. Yes. But don't forget that the topic requires a reverse order in place, that is, does not allow additional space allocated, then the parameter is definitely a character array form, because the string cannot be modified (here is only the string constant in C/s + +), so the array is related to it, but not an integer arrays, but a character array. With two pointers pointing to the first of the character array, exchanging their corresponding characters, and then moving the two pointers to the center of the array, respectively, until they intersect.
Code
string reverse order void Reverse (char*a, int n) { int left =0; int right = n-1; while (left < right) { Char temp = a[left]; a[left++] = A[right]; a[right--] = temp; }}
Combinatorial issues
Given an integer array of n elements a, from which any m element is taken, all combinations are obtained. such as the following example
A = 1, 2, 3, 4, 5
m = 3
Output
1 2 3, 1 2 4, 1 2 5, 1 3 4, 1 3 5, 1 4 5
2 3 4, 2 3 5, 2 4 5
3 4 5
Analysis
A typical permutation problem, the preferred backtracking method, to simplify the problem, we set the N element value of a to 1-n
Code
n Select all combinations of M int buffer[100]; void PrintArray (int *a, int n) {for (int i = 0; i < n; ++i) cout << A[i] < < ""; cout << Endl;} BOOL IsValid (int lastIndex, int value) {for (int i = 0; i < LastIndex; i++) { if (Buffer[i] >= value)
return false; } return true;} void Select (int t, int n, int m) { if (t = = m) PrintArray (buffer, m); else {for (int i = 1; I <= n; i++) { buffer[t] = i; if (IsValid (t, i)) Select (t + 1, N, m);}}}
Merging two arrays
Given two ordered (non-descending) integer arrays A and b that contain n elements. Merging elements from two arrays into an integer array c requires removing duplicate elements and keeping C in order (not descending). Examples are as follows
A = 1, 2, 4, 8
b = 1, 3, 5, 8
c = 1, 2, 3, 4, 5, 8
Analysis
Using the idea of merging sorting, the two pointers i,j and K point to the array A and B respectively, and then compare the size of the two pointers to the corresponding elements in the following three cases
1. A[i] < B[j], then c[k] = A[i].
2. a[i] = = B[j], then c[k] is equal to a[i] or b[j].
3. A[i] > B[j], then c[k] = B[j].
Repeat the process until I or J reaches the end of the array, and then copy the remaining elements directly into the array C
Code
Merges two ordered arrays of void merge (int *a, int *b, int *c, int n) { int i = 0; int j = 0; int k = 0; while (I < n && J < N) { if (A[i] < B[J])//If the element A is small, insert a in element to C { c[k++] = a[i]; ++i; } else if (a[i] = = B[j])//If the A and B elements are equal, insert both, insert a { c[k++] = a[i]; ++i; ++j; } else//a[i] > B[j]//If the elements in B are small, insert the elements in B to C { c[k++] = b[j]; ++j; } } if (i = = N)//If a traversal is complete, the remaining elements in B are processed {for (int m = j; m < n; ++m) c[k++] = b[m]; } Else//j = = N, if the B traversal is complete, the remaining elements in a are processed {for (int m = i; m < n; ++m) c[k++] = a[m]; }}
Reflow problem
Given an integer array of n elements, a containing 0 elements and non-0 elements, sorting the array, requires:
1. After sorting all 0 elements before, all non-0 elements are behind, and non-0 elements are sorted before and after the relative position unchanged
2. Cannot use additional storage space
Examples are as follows
Input 0, 3, 0, 2, 1, 0, 0
Output 0, 0, 0, 0, 3, 2, 1
Analysis
This sort is not a traditional sort, because it requires that the relative position of the non-0 elements be the same before and after the sort, perhaps called collation would be more appropriate. We can traverse the entire array from the back forward, and if the element on the I is a non-0 element, if A[k] is 0, assign a value of a[i] to A[k],a[k] to 0. I am actually subscript for a non-0 element, and K is the subscript for the 0 element
Code
void Arrange (int* a, int n) { int k = n-1; for (int i = n-1; I >=0; I.) { if (A[i]!=0) { if (A[k] ==0) { a[k] = a[i]; A[i] =0; } --k;}}}
Find the element with the smallest absolute value
Given an ordered integer sequence (non-descending order), it may contain negative numbers to find the element with the smallest absolute value, such as the given sequence-5,-3,-1, 2, 8 returns 1.
Analysis
Because the given sequence is ordered, and this is the search problem, so first think of binary search method, but this dichotomy is slightly more troublesome than the ordinary dichotomy, can be divided into the following situations
- If all the numbers in the given sequence are positive, then the first element of the array is the result.
- If all the numbers in the given sequence are negative, then the last element of the array is the result.
- If the given sequence has both positive and negative values, it is absolutely worth the minimum value to be at the junction of positive and negative numbers.
Why? Because for a negative sequence, the number on the right is smaller than the number on the left, such as 5,-3, 1, and for an entire number, the absolute value of the left is small, such as the above 2, 8, the idea for a binary search, you can first determine the middle element and the two elements of the symbol, and then determine the search interval Gradually narrow the search interval until only two elements are left.
Code
Set a function individually to determine whether the symbols for the two integers are the same.
BOOL Samesign (int a, int b) { if (A * b > 0) return true; else return false;}
The main function code.
Find the smallest absolute number in a non-descending sequence integer sequence int minimumabsolutevalue (int* A, int n) {//Only one digit in array if (n ==1) { R Eturn a[0]; } All numbers in array has the same sign if (Samesign (a[0], a[n-1])) { return a[0] >=0? A[0]: a[n-1]; } Binary search int l =0; int r = n-1; while (L < R) { if (L +1== r) { return abs (A[l]) < ABS (A[r]) a[l]: A[r]; } int m = (L + r)/2; if (Samesign (A[m], a[r])) { r = m-1; Continue; } if (Samesign (A[l], a[m])) { L = m +1; Continue;}}}
This code is a problem, thank the Netizen lingyunfish correction, you see it? The modified code is as follows:
Find the smallest absolute number in a non-descending sequence integer sequence int minimumabsolutevalue (int* A, int n) {//Only one digit in array if (n ==1) { R Eturn a[0]; } All numbers in array has the same sign if (Samesign (a[0], a[n-1])) { return a[0] >=0? A[0]: a[n-1]; } Binary search int l =0; int r = n-1; while (L < R) { if (l + 1 = = r) { return abs (A[l]) < ABS (A[r])? A[l]: A[r]; } int m = (L + r)/2; if (Samesign (A[m], a[r])) { r = m; Continue; } else { L = m; Continue;}}}
Array Polygon Questions