Recently in the cattle to tidy up a number of commonly used algorithm ideas, "Common algorithm Thinking Analysis series" is mainly aimed at some high-frequency algorithm written test, interview problem solving ideas to summarize, most also give a specific code implementation, this article is a sort of related topics of thought analysis.
1. Simple classification
First, some of the commonly used algorithms are categorized by spatial complexity as follows:
O (1):
Bubble sort, select sort, insert sort, hill sort, heap sort
O (Logn) ~o (N):
Quick Sort
O (N):
Merge sort
O (M):
Count sort, base sort
2, to a basic ordered array ordering, choose which sort algorithm? Basic Order: If the array is ordered, the distance between each element is not greater than k, and K is small relative to the array length.
(1) for sorting algorithm with time complexity O (N): (Count sort, cardinal sort) for the above two algorithms, because do not know the expression range of the elements in the array,not suitable for!
(2) Sorting algorithm with time complexity O (N2)Insert Sort: According to the title, the basic ordered elements, each element moving distance is not more than k, so the insertion of the order of each element moving forward is not more than K, so when the insertion sort time complexity of O (n*k), belong toO (N2) A better implementation in this case。 (3) Sorting algorithm with time complexity O (N*LOGN)Quick Sort: independent of the original order of the array, each time a random selection of an element to divide, so this is still O (N*logn), is a good O (N*logn).Merge Sort:Similarly, it is independent of the original order of the array. Also is good at this time still O (N*logn).
one of the best : improved heap ordering
(See this summary article: [Big, small Gan application Summary One] heap sort of application scenario)
The code is implemented as follows:
public static int[] Heapsort (int[] A, int n, int k) {if (A = = NULL | | A.length = = 0 | | N < k) {return null; } int[] heap = new Int[k]; for (int i = 0; i < K; i++) {heap[i] = A[i]; } buildminheap (heap,k);//first set up a small heap for (int i = k; i < n; i++) {A[i-k] = heap[0];//difficulty heap Top min element Heap[0] = A[i]; Adjust (heap,0,k); } for (int i = N-k;i < n; i++) {a[i] = heap[0]; Heap[0] = heap[k-1]; Adjust (heap,0,--k);//reduce the range of adjustments} return A; }//Build a small Gan private static void Buildminheap (int[] A, int len) {for (int i = (len-1)/2; I >= 0; I- -) {adjust (A,i,len); }}//Downward adjustment, making the property of re-compounding small Gan private static void adjust (int[] A, int k, int len) {int temp = a[k]; for (int i = 2 * k + 1; i < len; i = i * 2 + 1) {if (I < leN-1 && a[i+1] < a[i])//If there is a right child node, and the right child node value is less than the left Haizi node value i++;//take K smaller sub-node subscript if (Temp < = A[i]) break;//filter end, without downward adjustment else{//need to adjust downward a[k] = a[i]; K = i;//k point to the new node that needs to be adjusted}} A[k] = temp;//The value that needs to be adjusted is finally placed at the last node to be adjusted}
3. Determine if there are duplicate values in the array, requiring a space complexity of O (1)
(1) ifno space complexity limitUseHash Table Implementation。 For example, using HashMap (or using the ASCII value of a character as an int array for subscript), the time complexity is O (n) and the spatial complexity is O (n). (2) In the case of space complexity limitations, we cansort first, then JudgeThe idea. Because of the order, duplicate values are placed in adjacent positions.
At this point, the problem is converted to,When space complexity is limited to O (1), the classical sorting algorithm is investigated ., how to implement one of the fastest algorithms. Based on the spatial complexity of the above statistics, you can know that the use of non-recursive implementation of the heap sorting the fastest.(see this summary article for details:[Big, small Gan application Summary One] heap sort of application scenario)The implementation code is as follows:
public static Boolean checkduplicate (int[] A, int n) {if (a = = NULL | | a.length = = 0 | | a.length = = 1) r Eturn false; Heapsort (A,n); for (int i = 1; i < n; i++) {if (a[i] = = A[i-1]) {return true; }} return false; } private static void Heapsort (int[] a,int N) {for (int i = (n-1)/2; I >= 0; i--) {Adjustdown (a,i , n); } int temp; for (int i = n-1; i > 0; i--) {//only need n-1 trip temp = a[0];//swap heap top element a[0] = A[i]; A[i] = temp; Adjustdown (A,0,i); }} private static void Adjustdown (int[] A, int k,int n) {int temp = a[k]; for (int i = 2 * k + 1; i < n; i = i * 2 + 1) {if (I < n-1 && A[i] < a[i+1])//Have right child node, and have child node value greater than left Haizi node value, will I point to the right child i++; if (temp >= a[i]) break; else{//need to adjust downward a[k] = a[i]; K = i;//points to the new node that may need to be adjusted}} A[k] = temp; }
4, merge two ordered arrays into an array, the first array space can fit the elements of two arrays exactly
For example, arrays A, B are ordered, a can hold two elements of an array. Idea: can be fromthe end of A, b begins to traverse the comparison, placing the larger element at the end of a, go down in sequence ... The key here is to start at the end of A and b so that you can keep a useful part of a as far as possible. The code is implemented as follows:
public static int[] Mergeab (int[] A, int[] B, int n, int m) { if (A = = NULL | | B = = NULL | | A.length < n+m) { return null; } int k = n + m-1; int i = subscript indicator for n-1;//a int j = Subscript m-1;//b while (i >= 0 && J >= 0) { if (A[i] < b[j]) { a[ k--] = b[j]; j--; } else{ a[k--] = a[i]; i--; } } if (J >= 0) {//means there are elements in data B, place the remaining elements of B in front of a while (k >= 0 && J >= 0) { a[k--] = b[j--]; } } return A; }
5. Question of the flag of the Netherlands
The array that contains only the values of the 0,1,2 three elements is sorted so that all 0 are on the left of 1, all 1 in the middle, and all 2 on the right of 1. Requires the use of swapping, in-place sorting, rather than counting.
The main process is similar to the fast-line partitioning process , which defines two pointers i0 and I2, pointing to 0 regions and 2 regions, traversing from the beginning, encountering 1, continuing, encountering 0, swapping the last bit of the 0 region (the first bit of the 1 zone), and the element that the current traversal points to. Then the 0 area is scaled back one bit, and the2 area is enlarged one by 2, the previous bit (that is, the 1 zone) of the interchange 2 region, and the element that the current traverse points to.
The time complexity is O (n) and the spatial complexity is O (1). The code is implemented as follows:
public class Threecolor {public static void main (string[] args) {int[] a = {1,1,0,2,1,0,1,0,2,1,2,1,1,0,2,2 , 1}; Sortthreecolor (a,a.length); for (int i = 0; i < a.length; i++) {System.out.print (a[i]+ ""); }} public static int[] Sortthreecolor (int[] A, int n) {int i0 = -1;//pointer to 0 area, 0 Zone initial size is 0 int i2 = n;/ /Pointer to 2 area, 2 Initial size of 0 int temp; for (int i = 0; i < i2; i++) {//NOTE!!! , here is i<i2, that is, less than 2 of the position of the region if (a[i] = = 1) continue; if (a[i] = = 0) {//Exchange 0 The last bit of the area and I point to the element temp = A[i]; A[i] = a[i0 + 1]; A[i0 + 1] = temp; 0 The region extends backward one i0++; }else if (a[i] = = 2) {//Interchange 2 The first bit of the area and I point to the element temp = A[i]; A[i] = a[i2-1]; A[I2-1] = temp; 2 The area extends one i2--; Attention!!! Since the data element in front of the 2 area is not searched, the pointer I shouldShould stay in place, here first-1 in for +1, equivalent to I did not change i--; }} return A; }}
6, ordered matrix (two-dimensional array) lookup
Now that there is a matrix of rows and columns in order, design an efficient algorithm to quickly find out if the matrix contains the value x.
given an int matrix mat, given the matrix size nxm and the number of xto be searched, return a bool value that represents whether x exists in the matrix. The numbers and x in all matrices are integers within the int range. Ensure that both N and m are less than or equal to 1000. specific thinking analysis, see: [Sword Point offer] Find in a two-dimensional array
The time complexity is O (m+n), the code is as follows:
public static Boolean Findx (int[][] mat, int n, int m, int x) {//from the lower left corner of The matrix (only from the lower-left or upper-right corner, only these two corners conform to the characteristics of the binary sort tree) int i = n-1; int j = 0; while (i >= 0 && J < m) { if (mat[i][j] = = x) return true; if (x < mat[i][j]) { i--; } else{ j + +; } } return false; }
7, the shortest sort subarray: for an array, design an efficient algorithm to calculate the length of the shortest subarray that needs to be sorted
given an int array
of size
n, the minimum subarray length that the array needs to sort is computed. (The original sequence position is labeled starting from 0, Wakahara sequence, return 0). Ensure that the elements in a are positive integers.
Test examples:
[1,4,6,5,9,10],6
Returns: 2
Solution: It is necessary to calculate the position of the previous sequence, and the position of the sequence. The time complexity is O (N), the space complexity is O (1), the code is as follows:
public static int shortestsubsequence (int[] A, int n) { //left and right initial order one equal!!! Represents a possibly initial ordered int left = 0;//follows a right-to-right position in a process that needs to be sorted by an int. = 0;//follows a left-to-right procedure where an order needs to be sorted if (a = = NULL | | n = = 0 | | n = = 1 ) { return 0; } int max = a[0]; int min = a[n-1]; for (int i = 0; i < n; i++) {//////////////////////to the maximum value in the Traverse, and compare it to the current value if (A[i] > Max) max = a[i]; if (A[i] < max) right = i;//corresponds to the position of the record to the rightmost need to sort } for (int i = n-1; I >= 0; i--) {//And then from right to left, record the minimum value in the Traverse, and The current value is compared if (A[i] < min) min = a[i]; if (A[i] > min) left = i;//is the equivalent of the record to the leftmost position to be sorted } if (Ieft = right) return 0; else return right-left + 1; }
8. The maximum difference between two adjacent numbers
There is a shape array A, design an algorithm with a complexity of O (n), and calculate the maximum difference between two adjacent numbers
after sorting .
The optimal solution time complexity is O (n), the space complexity is O (n), the code is as follows:
public static int Maxgap (int[] A, int n) {if (A = = NULL | | n < 2) return 0; int min = a[0]; int max = a[0]; for (int i = 1; i < n; i++) {if (A[i] > max) max = a[i]; if (A[i] < min) min = a[i]; Float gap = (max-min) * 1.0f/n;//divides max-min into n equal boolean[] Hasnum = new Boolean[n + 1];//current bucket number whether there are elements inside int[] Maxs = new Int[n + 1];//holds the maximum value in a bucket int[] mins = new Int[n + 1];//holds the minimum value in a bucket for (int i = 0; I < ; N i++) {int p = (int) ((a[i]-min)/gap); Calculates the current element's owning bucket number if (Hasnum[p]) {//If the bucket number already has a value maxs[p] = Maxs[p] < A[i]? A[i]: maxs[p]; MINS[P] = Mins[p] > a[i]? A[i]: mins[p]; }else{maxs[p] = a[i]; MINS[P] = A[i]; } Hasnum[p] = true; } int i = 0; int res = 0; int Lastmax = 0; while (i <= N) { if (hasnum[i++]) {//Find the first bucket with an element Lastmax = maxs[i-1];//i++; Break }} while (I <= N) {if (Hasnum[i]) {res = mins[i]-lastmax > Res? mins[i]- Lastmax:res; Lastmax = Maxs[i]; } i++; } return res; }
Some of the above topics are not specifically analyzed, but in the code implementation has added comments, manual simulation should be no problem. The next article will summarize the "common Algorithm Thinking Analysis series" string-related topics.
"Common Algorithm Thinking Analysis series" Sorting high Frequency problem sets