📌  相关文章
📜  通过将每个元素的第一次出现增加 K 来修改给定数组

📅  最后修改于: 2021-10-27 09:09:21             🧑  作者: Mango

给定一个由N 个整数组成的数组 arr[] ,将数组中的每个元素一一读取并执行以下操作:

  • 如果当前元素arr[i]先前已出现在数组中,则将其第一次出现的次数增加K
  • 否则,将arr[i]插入序列中

任务是打印通过执行上述操作获得的最终整数序列

例子:

朴素的方法:解决问题最简单的方法是遍历数组,对于每个数组元素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)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程。