给定一个未排序的整数数组,其中可能包含重复元素,按其出现的降序对元素进行排序。如果存在多个元素的出现次数总和相同,则较大的元素将排在第一位。
例子:
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,但如果出现 m 次,则 a 将映射到 a*m。
- 完成映射后,根据字典的值而不是键按降序对字典进行排序。在平局的情况下,根据值排序。
- 最后复制最终输出数组中排序的字典键,并根据它们的键值对获得频率,即如果 a 映射到 a*m,则意味着我们需要在输出数组中包含 a, 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)。
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live