给定一个未排序的整数数组,其中可能包含重复的元素,请按出现次数降序对元素进行排序。如果存在不止一个元素,其出现的总和相同,那么将首先出现较大的元素。
例子:
Input: arr[] = [2, 4, 1, 2, 4, 2, 10]
Output: arr[] = [10, 4, 4, 2, 2, 2, 1]
Explanation:
Here, 2 appears 3 times, 4 appears 2 times, 1 appears 1 time and 10 appears 1 time.
Thus,
Sum of all occurrences of 2 in given array = 2 * 3 = 6,
Sum of all occurrences of 4 = 4 * 2 = 8,
Sum of all occurrences of 10 = 10 * 1 = 10,
Sum of all occurrences of 1 = 1 * 1 = 1.
Therefore sorting the array in descending order based on the above sum = [ 10, 4, 4, 2, 2, 2, 1 ]
Input2: arr[] = [2, 3, 2, 3, 2, 1, 1, 9, 6, 9, 1, 2]
Output2: [9, 9, 2, 2, 2, 2, 6, 3, 3, 1, 1, 1]
方法:
- 创建一个将元素映射到其外观的映射,即,如果发生一次,则a将映射到a,但是如果发生一次,则a将映射到a * m。
- 进行映射后,根据字典的值而不是键,以降序对字典进行排序。如果是平局,则根据值排序。
- 最后将排序后的字典键复制到最终输出数组中,然后根据其键值对获得频率,即,如果将a映射到a * m,则意味着我们需要在输出数组中包含m次。
下面是上述方法的实现:
Python
# Python3 program to sort elements of
# arr[] in descending order of sum
# of its occurrence
def sort_desc(arr):
# to store sum of all
# occurrences of an elements
d_sum = {}
# to store count of
# occurrence of elements
d_count ={}
# to store final result
ans = []
# to store maximum sum of occurrence
mx = 0
# Traverse and calculate sum
# of occurrence and count of
# occurrence of elements of arr[]
for x in arr:
if x not in d_sum:
d_sum[x] = x
d_count[x] = 1
else:
d_sum[x] += x
d_count[x] += 1
# sort d_sum in decreasing order of its value
l = sorted(d_sum.items(),
reverse = True,
key = lambda x:(x[1], x[0]))
# store the final result
for x in l:
ans += [x[0]] * d_count[x[0]]
return ans
# Driver Code
arr = [3, 5, 2, 2, 3, 1, 3, 1]
print(sort_desc(arr))
[3, 3, 3, 5, 2, 2, 1, 1]
时间复杂度: O(N * log N)。
空间复杂度: O(N)。