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

Source: Internet
Author: User
Tags array length

* 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

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.