PHP array of some common operations summary _php tips

Source: Internet
Author: User
Array summation
Given an integral array of n elements, a, to the and of all elements in a. Perhaps you will feel very simple, yes, it is simple, but why say it, the reason is two, first, this problem requires recursive method, only one line of code. Second, this is the first time in my life, the problem encountered in the interview, the significance of special.

To put it simply, two things:

If the array element number is 0, then the and is 0.
If the number of elements of an array is n, then the sum of the first n-1 elements, plus a[n-1] can be obtained.
Copy Code code 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 integral array of n elements, a, find the maximum and minimum values.

The general practice is to traverse it once, find out the maximum and the minimum, but what I'm going to say here is the divide-and-conquer method (Divide and Couquer), which divides the array into the left and right parts, first finding the maximum and minimum value of the left-hand part, and then finding the maximum and minimum value of the right-hand part. The maximum and minimum values of the population are then combined. This is a recursive process, and for the left and right parts of the partition, repeat the process until there is only one element or two elements left in the dividing range.
Copy Code code as follows:

The maximum and minimum values of the array are evaluated, and the return value is in MaxValue and MinValue
void maxandmin (int *a, int l, int r, int& maxValue, int& minvalue)
{
There is only one element between the IF (L = = r)//L and R
{
MaxValue = A[l];
MinValue = A[l];
return;
}

There are only two elements between if (L + 1 = r)//L and R
{
if (A[l] >= a[r])
{
MaxValue = A[l];
MinValue = A[r];
}
Else
{
MaxValue = A[r];
MinValue = A[l];
}
return;
}

int m = (L + r)/2; Ask for the midpoint

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

int Rmax; Right half part maximum value
int rmin; Right half part 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 integral array of n elements, the maximum value and the secondary large value are obtained.

The idea is similar to the previous one, it is also divided into the rule, not much said, directly look at the code:

Copy Code code as follows:

The maximum and secondary values of the array are evaluated, and the return value is 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;
}
}


To find an element with more than half occurrences in the array
Given an array of n integral elements, one of which has an element that appears more than N/2, ask for this element. Baidu is said to be a face test.

Sets a counter for the current value and the current value, initializes the current value as the first element, the counter value is 1, and then iterates through the entire array from the second element, a[i for each value that is traversed.

If A[i]==currentvalue, the counter value is plus 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 of a[i] and reset the counter value to 1.
Copy Code code as follows:

Find more than half of the elements in the 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, and then take the middle element, because if an element is more than half, the element must occupy the middle position of it after the array is sorted.

To find the shortest distance of an element in an array
Given an integral array of n elements, finding two elements x and y in the array makes the ABS (X-y) the smallest.

Sort the array first, then traverse it once:

Copy Code code 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<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 (not descending) integer arrays of n elements, A and B, 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 arrays, with two pointers I and J respectively pointing to A and B, comparing a[i] and b[j], moving the pointer according to the results of the comparison, there are three cases:

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

Copy Code code as follows:

Find a common element 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 binary search in B for any element of a, 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 the B order can, a is not orderly, because we just do binary Search in B. If a is also orderly, then the above method is a bit slow, because if the position of an element in a in B is k, then the position of the next element in a in B must be on the right side of K, so this search space can be reduced based on the last search result rather than still searching throughout B. That is, if both A and B are in order, the code can be modified to record the position of the elements in B at the time of the last search, as the starting point for the next search.

Find a common element of three arrays
Given the three integer arrays containing n elements, a,b and C, ask for their smallest common element.

If the three arrays are ordered, you can set three pointers to the head of three arrays, and then move the pointer based on the values that the three pointers refer to, until a common element is found.

Copy Code code 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 three arrays are unordered, you can sort a, B, and then do a binary search for any element in C in B and C.
Copy Code code 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 is 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 element in B and C in a.
Copy Code code 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 to 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 code is as follows:
Copy Code code 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 sum up, the problem of finding in an array can be dealt with in two different cases:

If the given array is ordered, then the first thing you should think of is binary Search, the desired O (logn).
If the given array is unordered, the first thing to do is to sort the arrays, and many sort algorithms can sort the arrays in O (NLOGN) time, then use the binary search, and the total time complexity is still O (Nlogn).
If you can do the above two points, most of the search problem of the array, can be solved.

Find the only repeating element in the array
Given an array of 1001 elements, which holds integers within 1-1000, and only one integer is duplicated, find this number.

To find the entire array of the and, minus 1-1000 and then, the code slightly.

Find the elements that appear in the odd number of times
Given an integral array of n elements, a, where only one element appears odd several times, find this element.

Because for any number k, there is k ^ k = 0,k ^ 0 = k, so that all the elements in a is different or, then the number of even elements are changed to 0, leaving only the odd number of that element.

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

for (int i = 1; i
To find the number of pairs in the array that satisfy the given
Given an array of two ordered integers a and b, each has n elements, and a given and a number of pairs in the two array, which is the element j of the elements I and b in a, satisfies i + j = d (known as D).

Two pointers I and J point to the end of the array, and then traverse from both ends to the middle until the two pointers cross.
Copy Code code as follows:

Find the number of pairs that meet the given
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 segment and
Given an integer array A, the sum of the maximum contiguous segments is computed, and if the sum is negative, then 0 is calculated, such as 1, 2,-5, 6, 8, and the output is 6 + 8 = 14.

Programming Zhuji on the classic topic, not much said.
Copy Code code as follows:

The most Yamato of the child 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 feet A, the product of the maximal contiguous segment is obtained, for example 1, 2,-8, 12, 7 is output 12 * 7 = 84.

With the largest segment and similar, note the case of handling negative numbers.
Copy Code code as follows:

Maximum product of a child 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 rotation shift
A problem that is seen in the beauty of Microsoft's programming is that an array with n elements is rotated to the right by a K-bit, requiring a time complexity of O (n) and only two additional variables.

For example, the array 1 2 3 4 loop Right Shift 1 will become 4 1 2 3, observed that the order of 1 2 3 is not changed before and after the shift, but the position of 4 is exchanged, 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 reverse back to get 3 2 1 4, and finally the whole order to get 4 1 2 3.
Copy Code code as follows:

Reverse the element 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;
}
}

Converts an array containing n elements to the right 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);
}

String reverse
Given a character array of n elements, reverse it in place.

You might think it's not about arrays, it's about strings. Yes. But don't forget that the problem requires a reverse order, that is, no extra space is allowed, so the argument is definitely a character array, because the string cannot be modified (here is only a string constant in C + +), so the array is concerned, but not an integer array, but a character array. Point to the first of the character array with two pointers, swap the corresponding characters, and then move the two pointers to the center of the array until they cross.
Copy Code code as follows:

String reverse
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 problems
Given an integral array of n elements, A, from which m elements are taken, all combinations are obtained. For example, the following examples:

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 N-element values in a to 1-n respectively for the typical permutation and combinatorial problems.
Copy Code code as follows:

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 an array of two ordered (not descending) integers with n elements, A and B. Merging elements from two arrays to integral array C requires removing duplicate elements and keeping C ordered (not descending). Examples are as follows:

A = 1, 2, 4, 8
b = 1, 3, 5, 8
c = 1, 2, 3, 4, 5, 8

With the idea of merging sort, two pointers i,j and K point to array A and B, and then compare the size of two pointers to the corresponding elements, with 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 the array C.
Copy Code code 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 of a is small, insert the element in a to C
{
c[k++] = A[i];
++i;
}
else if (a[i] = = B[j])//If the A and B elements are equal, insert either, insert a
{
c[k++] = A[i];
++i;
++j;
}
else//a[i] > B[j]//If the element in B is small, insert element B into C
{
c[k++] = B[j];
++j;
}
}

if (i = = N)//If A is traversed, process the remaining elements in B
{
for (int m = j; m < n; ++m)
c[k++] = b[m];
}
else//j = n, if b traversal completed, processing the remaining elements of a
{
for (int m = i; m < n; ++m)
c[k++] = a[m];
}
}

Rearrange issues
Given an integral array of n elements, a, which includes 0 elements and a non-0 element, sorted by array, requires:

After all 0 elements are sorted, all non-0 elements are followed, and the relative positions of non-0 elements are not changed before and after the order.
No additional storage space is available.
Examples are as follows: input 0, 3, 0, 2, 1, 0, 0, output 0, 0, 0, 0, 3, 2, 1.

This sort is not the traditional sort, because it requires that the relative position of the 0 elements before and after the order be unchanged, perhaps called collation is more appropriate. We can iterate over the entire array from the back, and when we encounter an element in a location I that is a non-0 element, and if A[K] is 0, assign the A[i to A[k],a[k] to assign 0. In fact I am the subscript of a non 0 element, and K is the subscript of 0 elements.
Copy Code code 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;
}
}
}

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.