* Count the occurrences of each element in the array
* The array length is N, and the range of each element is [1,n].
* Count the number of occurrences of each element, requiring a time complexity of O (N) and a spatial complexity of O (1). You can modify the values of the elements in the array.
*
* Idea: Traverse to each element, the (element value-1) as the subscript value, the subscript of the element assignment (if positive, assignment-1; if negative,-1)
* Finally, the number of elements stored in each subscript is counted, and subscript +1 is the element value.
Code:
Public Static voidMain (string[] args) {//TODO auto-generated Method Stub intn = 6; int[] A =New int[]{6,2,4,1,2,5}; inti = 0; //using the while loop while(I <N) { //because the element value range is [1,n], you can use (the current element value-1) as the subscript value, find the element at the corresponding position, and store its value as-times, because the original stored value is positive, to prevent confusion, with negative values to store inttemp = A[i]-1; if(Temp < 0) {//indicates that the element has been processed and skippedi++; Continue; } Else if(A[temp] > 0) {//processing a value for the first timeA[i] = a[temp];//Staging new elementsA[temp] = 1; } Else{//It's not the first time this value has been processed.A[i]= 0;//no new elements to handle, set 0a[temp]--; } } for(intj = 0; J < N; ++j) {System.out.print (J+1 + "," +-a[j] + "\ T"); } }
The number of occurrences of each element in the statistical array [1-n], the time complexity O (n), the spatial complexity O (1), the array structure can be changed