给定一个由N 个整数组成的数组 arr[] ,将数组中的每个元素一一读取并执行以下操作:
- 如果当前元素arr[i]先前已出现在数组中,则将其第一次出现的次数增加K 。
- 否则,将arr[i]插入序列中
任务是打印通过执行上述操作获得的最终整数序列
例子:
Input: arr[] = {1, 2, 3, 2, 3}, K = 1
Output: [1, 4, 3, 2, 3]
Explanation:
Arrival : 1
Since 1 is the first element in the stream, simply insert it into the solution.
Therefore, b[] = [1]
Arrival: 2
Since 2 is not existing in the array, simply insert it into the solution.
Therefore, b[] = [1, 2]
Arrival: 3
Since 3 is not existing in the array, simply insert it into the solution.
Therefore, b[] = [1, 2, 3]
Arrival: 2
Since 2 already exists, increasing its first occurrence by K(=1)modifies the array b[] to [1, 3, 3, 2]
Arrival: 3
Since 3 already exists, increasing its first occurrence by K(=1)modifies the array b[] to [1, 4, 3, 2, 3]
Input: arr[] = {1, 4, 1, 1, 4}, K = 6
Output: [7, 10, 7, 1, 4]
朴素的方法:解决问题最简单的方法是遍历数组,对于每个数组元素arr[i] ,在范围[0, i – 1] 中遍历以检查数组中是否已经存在arr[i]或不。如果发现为真,则将arr[i]的第一次出现增加 K 。
时间复杂度: O(N 2 )
辅助空间: O(1)
高效的方法:可以使用 Hashing优化上述方法。请按照以下步骤解决问题:
- 遍历数组并将每个数组元素的出现存储在 Map 中,并按其出现的索引按递增顺序配对。
- 如果ARR [I]被发现是在地图已经存在,删除ARR [I]从地图中第一次出现。将该索引与arr[i] + K配对作为键插入回Map 。
- 对所有数组元素重复上述步骤。一次,遍历整个数组,从Map 中获取整数序列并打印最终序列。
下面是上述方法的实现:
C++
// C++ Program to implement
// the above approach
#include
using namespace std;
// Print the required final sequence
void printSequence(vector& A,
int n, int k)
{
// Stores the array element-index pairs
unordered_map > mp;
// Stores the required sequence
vector sol;
// Insert all array elements
for (int x : A)
sol.push_back(x);
for (int i = 0; i < n; i++) {
// If current element has
// not occurred previously
if (mp.find(sol[i]) == mp.end()
|| mp[sol[i]].size() == 0) {
mp[sol[i]].insert(i);
}
// Otherwise
else {
// Iterator to the first index
// containing sol[i]
auto idxx = mp[sol[i]].begin();
int idx = *idxx;
// Remove that occurrence
mp[sol[i]].erase(idxx);
// Increment by K
sol[idx] += k;
// Insert the incremented
// element at that index
mp[sol[idx]].insert(idx);
mp[sol[i]].insert(i);
}
}
// Print the final sequence
for (int x : sol) {
cout << x << " ";
}
}
// Driver Code
int main()
{
int N = 5;
int K = 6;
vector A = { 1, 4, 1, 1, 4 };
printSequence(A, N, K);
}
Javascript
7 10 7 1 4
时间复杂度: O(NlogN)
辅助空间: O(N)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live