You are given an array of integers and another target integer as input. Your task is to return the index or indices of the target integer in the array as if it were sorted, while adhering to a time constraint of O(n).
Example:
Input: [5, 6, 1, 2, 4], Target: 2
Output: [1]
Explanation: In the sorted version of the array [1, 2, 4, 5, 6], the target 2 appears at index 1.
Modify your solution to instead find the element or elements that appear most frequently in the array. Return the index or indices of these most frequent elements as if the array were sorted.
Example:
Input: [5, 6, 1, 2, 2, 4]
Output: [1, 2]
Explanation: Since 2 is the most frequent element and appears at indices 1 and 2 in the sorted array [1, 2, 2, 4, 5, 6].
Now, you need to return a new array of the same length where the elements are the indices of the original elements in a sorted version of the array.
Example:
Input: [5, 6, 1, 2, 4]
Output: [3, 4, 0, 1, 2]
Explanation: In the sorted array [1, 2, 4, 5, 6], 5, which is the first element of the original array, appears at index 3 in the sorted array, 6 at 4, 1 at 0, 2 at 1, and 4 at 2.
这道题本质上是在考“排序后的位置映射”。由于要求在 O(n) 时间内完成,不能直接排序整个数组,而是要利用计数或哈希统计每个值出现的次数,并根据值的大小关系推导它在有序数组中的排名。第一个版本要求返回目标值在排序数组中的下标;第二个版本扩展为返回出现次数最多的元素在排序数组中的所有下标;第三个版本则要求把原数组中每个元素映射成它在排序后数组里的位置,常见做法是先统计频次,再计算前缀排名,适合结合哈希表、计数数组或桶思想来处理。