给定一个由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)
高效的方法:可以使用哈希优化上述方法。请按照以下步骤解决问题:
- 遍历数组,并将每个数组元素的出现情况与它的出现索引按升序存储在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);
}
7 10 7 1 4
时间复杂度: O(NlogN)
辅助空间: O(N)