Title Requirements:
How to sort N numbers requires time complexity O (n). The spatial complexity is O (1).
Topic Analysis:
Strictly speaking, the condition given by this problem is not complete. If the size of these n numbers spans large (1~ infinity), then the requirement is certainly not reached.
If the size of n numbers is within a certain range (such as 0~65535), you can use the hash table method. defined as int hash[65536], occupying a memory space fixed to sizeof (int) *65536, the space complexity is O (1).
So how is the time complexity O (N)? That is, you can iterate through the array a few times to sort through. In fact, we can go through the array again, and then traverse through the hash space to output the sorted result.
As an example, for the sake of simplification, assuming that all numbers are between 0~10, define int hash[10] and initialize hash[0~9]=0;
The number of n in the original array is: {7,4,3,4,7,2,1,9}.
The first time in the group, each hash[a[i]]++ processing, so the result is hash[7]=2,hash[3]=1 ....
The second passes through the hash array, from hash[0]~hash[9], when hash[i] = x, continuously outputs X i. The result of this final output is 1 2 3 4 4 7 7 9.
The time complexity is O (N). The spatial complexity is O (1). Done ....
Code implementation:
#include <iostream>using namespacestd;Const intN =8;Const intHash_space =65536;voidSort (intA[],intNinthash[]);intMainvoid){ intA[n] = {7,4,3,4,7,2,1,9}; intHash[hash_space] = {0}; Sort (A,n,hash); return 0;}voidSort (intA[],intNinthash[]) { for(intI=0; i<n;i++) {Hash[a[i]]++; } for(intI=0; i) { while(Hash[i]) {cout<< I <<" "; Hash[i]--; }} cout<<Endl;}
A scary looking algorithm "Microsoft interview to 100 question 49th"