Some common operations summary for PHP arrays _php Tutorial

Source: Internet
Author: User
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.

To put it simply, two things:

If the number of array elements is 0, then the and is 0.
If the number of elements in the array is n, then the sum of the first n-1 elements, plus a[n-1] can be obtained first.
Copy CodeThe code is as follows:
Array summation
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.

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.
Copy CodeThe code is as follows:
The maximum and minimum values of the array are evaluated, and the return values are in MaxValue and MinValue
void maxandmin (int *a, int l, int r, int& maxValue, int& minValue)
{
if (L = = r)//L and R have 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; Find Midpoint

int Lmax; Left partial maximum value
int lmin; Left half minimum value
Maxandmin (A, L, M, Lmax, lmin); Recursive calculation of left half part

int Rmax; The right half of the maximum value
int rmin; Right half minimum value
Maxandmin (A, M + 1, R, Rmax, Rmin); Recursive calculation of the right half part

MaxValue = Max (Lmax, Rmax); The total maximum value
MinValue = min (lmin, rmin); The 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.

The thought and the previous question are similar, also uses the division and the method, does not say more, directly looks at the code:

Copy CodeThe code is as follows:
The maximum and secondary values of the array are evaluated, and the return values are in Max and second
void maxandmin (int *a, int left, int. right, int &max, int &second)
{
if (left = = right)
{
max = A[left];
Second = A[left];
}
else if (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 leftmin;
Maxandmin (A, left, Mid, Leftmax, leftmin);

int Rightmax;
int rightmin;
Maxandmin (A, mid + 1, right, Rightmax, rightmin);

max = Leftmax > Rightmax? Leftmax:rightmax;
Second = Leftmax < Rightmax? Leftmax:rightmax;
}
}


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. It is said that Baidu is a face test.

Sets a counter for the current value and 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].

If A[i]==currentvalue, the counter value is incremented by 1.
If a[i]! = CurrentValue, the counter value is reduced by 1, and if the counter value is less than 0, update the current value to A[i] and reset the counter value to 1.
Copy CodeThe code is as follows:
Find elements with more than half occurrences in an array
int Find (int* A, int n)
{
int curvalue = a[0];
int count = 1;

for (int i = 1; i

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 containing n elements, find the two elements x and y in the array to minimize the ABS (x-y) value.

Sort the array first, then iterate once:

Copy CodeThe code is as follows:
int compare (const void* A, const void* b)
{
return * (int*) A-* (int*) b;
}

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 :: 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 containing n elements, find common elements such as: a = 0, 1, 2, 3, 4 and B = 1, 3, 5, 7, 9, Output 1, 3.

Taking full advantage of the ordered nature of the array, using two pointers I and J respectively to A and B, comparing a[i] and b[j], and moving the pointer according to the comparison, there are three cases:

A[i] < B[j], then I add 1, continue to compare
A[i] = = B[j], then I and J both add 1, continue to compare
A[i]
Repeat the process until I or J reaches the end of the array.

Copy CodeThe code is as follows:
Find common elements of two arrays
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.

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.

Copy CodeThe code is as follows:
Common elements of three arrays-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.
Copy CodeThe code is as follows:
Find the unique common element in 3 arrays
O (NLOGN)
int Uniquecommonitem (int *a, int *b, int *c, int n)
{
Sort array A
Qsort (A, n, sizeof (int), compare); Nlogn

Sort Array B
Qsort (b, n, sizeof (int), compare); Nlogn

For each element in array C, does a binary search in A and b
This was up to a complexity of N*2*LOGN
for (int i = 0; i < n; i++)
{
if (BinarySearch (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.
Copy CodeThe code is as follows:
Find the unique common element in 3 arrays
O (NLOGN)
int UniqueCommonItem1 (int *a, int *b, int *c, int n)
{
Sort array A
Qsort (A, n, sizeof (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 each 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 each element in C, does a BS only if b[i] is true
for (int i = 0; i < n; i++)//Nlogn
{
if (B[i] && BinarySearch (A, n, C[i]))
return c[i];
}

return-1; Not found
}

The sorting and binary search codes are as follows:
Copy CodeThe code is as follows:
Determine whether a contains value K
BOOL 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 Qsort
int compare (const void* A, const void* b)
{
return * (int*) A-* (int*) b;
}

To summarize, the problem of finding in an array can be handled in the following two scenarios:

If the given array is ordered, you should first think of binary Search, which requires O (LOGN).
If the given array is unordered, the first thing you should think about is 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.

Find the entire array of the and, minus 1-1000 and can, 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.

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.

int findelementwithoddcount (int *a, int n)
{
int r = a[0];

for (int i = 1; i
Satisfies the given number pairs in the array
Given two ordered integer arrays A and B, each with n elements, the two array satisfies the given and the number pairs, that is, element I and B in a in element J, satisfies i + j = d (d known).

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.
Copy CodeThe code is as follows:
Find the number pairs that meet the given and
void Fixedsum (int* A, int* b, int n, int d)
{
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 maximal contiguous segments is calculated, and if and to a negative number, it is computed by 0, such as 1, 2, 5, 6, 8 output 6 + 8 = 14.

Programming Zhu Ji Nanxiong on the classic topic, not much to say.
Copy CodeThe code is as follows:
The largest of the sub-arrays
int Sum (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 integral number of a, calculate the product of the maximal contiguous sub-segments, such as 1, 2, 8, 12, 7 output 12 * 7 = 84.

As with the maximum sub-segment and similar, pay attention to the case of negative numbers.
Copy CodeThe code is as follows:
The maximum product of a sub-array
int maxproduct (int *a, int n)
{
int maxproduct = 1; Max positive product at current position
int minproduct = 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.

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, only with 4 position 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.
Copy CodeThe code is as follows:
Reverse the elements between start and end in buffer
void Reverse (int buffer[], int start, int end)
{
while (Start < end)
{
int temp = buffer[start];
buffer[start++] = buffer[end];
buffer[end--] = temp;
}
}

Moves the array with n elements to the right of the 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);
}

Reverse string
Given a character array a containing n elements, reverse it in place.

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.
Copy CodeThe code is as follows:
Reverse string
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. For example, the following:

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

In order to simplify the problem, we set the value of n elements in A to 1-n, which is a typical permutation and combination problem.
Copy CodeThe code is as follows:
All combinations of n selected 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

Using the idea of merging sorting, two pointers i,j and K point to arrays A and b respectively, and then compare the size of two pointers to the corresponding elements in the following three cases:

A[i]
A[i] = = B[j], then c[k] is equal to a[i] or b[j].
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 array C.
Copy CodeThe code is as follows:
Merging two ordered arrays
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 element A 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:

After sorting all 0 elements before, all non-0 elements are behind, and non-0 elements are sorted before and after the relative positions are unchanged.
Additional storage space cannot be used.
Examples are: input 0, 3, 0, 2, 1, 0, 0, output 0, 0, 0, 0, 3, 2, 1.

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. In fact I is the subscript of a non-0 element, and K is the subscript of the 0 element.
Copy CodeThe code is as follows:
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;
}
}
}

http://www.bkjia.com/PHPjc/323992.html www.bkjia.com true http://www.bkjia.com/PHPjc/323992.html techarticle The array sum is given an integer array of n elements, a, and the sum of all the elements in a. You might think it's simple, yes, it's simple, but why do you have to say it for two reasons ?

  • 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.