C++程式:用大於前一個重複值替換重複值


本文介紹了一系列整數。假設我們有一個包含四個元素的陣列(不計算重複元素),[2, 2, 5, 5, 7, 8, 7],我們需要使陣列變得獨特。我們可以將一個值更改為大於前一個值的值。

在上面的陣列中,索引1處的元素2變為3,因為它是下一個更大的元素。索引3處的5變為6,依此類推。因此,最終我們的陣列變為[2 3 5 6 7 8 9],並且在過程中應最大程度地減少元素的總和。

讓我們來看一些輸入場景 -

假設給定的輸入字串每個元素都有一個重複項,則獲得的結果為 -

Input: [1, 1, 2, 2, 4, 4, 6, 6]
Result: [1 2 3 4 5 6 7 8]

假設給定的輸入字串只有一個元素有多個重複項,則獲得的結果為 -

Input: [1, 1, 1, 1, 1, 1]
Result: [1 2 3 4 5 6]

由於新值必須大於前一個重複值,因此獲得一個序列。

示例(使用向量ADT)

以下是用C++編寫的程式,用於用大於前一個重複值的值替換陣列中的重複元素 -

#include <iostream> #include <vector> #include <set> using namespace std; void solve(vector<int>& arr) { set<int> s; for(int &val : arr) { if(s.find(val) != s.end()) { for(int j=val+1;j<INT32_MAX;j++) { if(s.find(j) == s.end()) { val = j; break; } } } s.insert(val); } } void print(vector<int>& arr) { for(int val : arr) cout << val << " "; cout << "\n"; } int main() { vector<int> arr = { 5,2,5,7,8,8,7 }; print(arr); solve(arr); print(arr); return 0; }

輸出

5 2 5 7 8 8 7
5 2 6 7 8 9 10

示例(不使用向量ADT)

以下是用C++編寫的程式,用於在不使用向量抽象資料型別的情況下用大於前一個重複值的值替換陣列中的重複元素 -

#include <bits/stdc++.h>
using namespace std;

int main()
{
   int array[] = { 1, 7, 2, 3, 4, 4, 5, 6, 6 };
   int n = sizeof(array) / sizeof(array[0]);
   for (int i = 0; i < n; i++)
      cout << array[i] << " ";
   cout << "\n";
   unordered_set<int> set;

   for (int i = 0; i < n; i++) {

      // check whether the element in a set is repeated or not
      if (set.find(array[i]) == set.end())
         set.insert(array[i]);

      else {
         for (int j = array[i] + 1; j < INT_MAX; j++) { // finding the next maximum element
            if (set.find(j) == set.end()) {
               array[i] = j;
               set.insert(j);
               break;
            }
         }
      }
   }
   for (int i = 0; i < n; i++)
      cout << array[i] << " ";
   cout << "\n";
}

輸出

1 7 2 3 4 4 5 6 6 
1 7 2 3 4 5 6 8 9 

結論

使用1個for迴圈遍歷陣列,我們將元素儲存在集合中。然後使用另一個for迴圈,我們找到下一個最大值,我們可以用它替換。這裡我們使用集合作為雜湊對映。我們也可以在這裡使用unordered_map或map。

更新於: 2022年8月10日

255 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.