topic:
Solution One: compare elements are equal
Idea Explanation:
This should be the first solution that ordinary people think of, first get to the array after the small to large sort, and then initialize a min=0 (representing the beginning of the new number), and then iterate over each element of the new array, if two elements are not equal, Count equals i-min, and then I assigned to Min, When I traverse to the last element, count equals the length of the array-min (here's min is the first element of the last set of numbers after the round loop), of course the interviewer will not like this solution.
(m, n) = input (). Split ()
AR = [int (x) for x into input (). Split ()]
res = []
ar.sort ()
min = 0 for
i in RA Nge (1,len (AR)):
if ar[i-1]!= Ar[i]:
count = i-min
min = i
res.append (str (count))
if i = = (Len (AR )-1:
count = Len (ar)-min
res.append (str (count))
print ('. Join (RES))
solution two: Bucket calculation
Train of thought: get to the input array, get the length of the array, because according to the topic n<=20, that is, the elements of the array is not more than 20, then we define a 1-D, 20-length array res, and initialization element of 0 is sufficient. First the code, then the parsing
(m, n) = input (). Split ()
AR = [int (x) for x into input (). Split ()] result
= []
res = [0 for x in range]
F Or a in AR:
res[a-1]+=1 for
R in Res:
if r!= 0:
result.append (str (r))
print (". Join (Result)")
And the core code is the two lines
For a in AR:
res[a-1]+=1
We iterate through the input array ar every element, with the value of Res[a] represents a number of occurrences, we each cycle, always find the right bucket to store A, then we can directly +1, such as AR = [2, 2, 1, 4]
Cycle 1:
A = 2
RES[2] = 0+1 = 1
Cycle 2:
A = 2
RES[2] = 1 +1 =2
Cycle 3:
A = 1
Res[1] = 0+1 = 1
Cycle 4:
A = 4
RES[4] = 0+1 = 1
So we get res = [0, 1, 2, 0, 1, 0] Extend: Bucket sort
Based on the above ideas we get a new array res, and carefully analyze the meaning of this array, 1 appears 1 times, 2 appears 2 times, 4 appears 1 times, because the characteristics of the array to ensure that the elements of the angle is small to large sort, which derives the concept of the bucket, ignoring the 0 situation, with two loops, the outer loop traversal Len ( RES) times, the angle is labeled I, the inner loop traversal res[i] times, the angle mark is J, the meaning is has several output several, for example 1 has 1, that output 1, 2 has two, on the circulation two times, the output two times, 4 has 1, on output One, expands the code as follows:
#省略上述代码 for
i in range (len (res)):
if Res[i]!= 0: With
J in range (Res[i]):
result.append (i)
print ( Result
The results of the implementation are as follows: