使用 C++ 列印給定整數陣列的所有不同元素


在這個問題中,我們給定一個整數陣列。我們的任務是列印陣列中的所有不同元素。輸出應該只包含不同的值。

讓我們舉個例子來理解這個問題

Input: array = {1, 5, 7, 12, 1, 6, 10, 7, 5}
Output: 1 5 7 12 6 10

為了解決這個問題,我們將不得不檢查陣列元素的唯一性。為此,我們將使用兩個巢狀迴圈,外部迴圈將取值,內部迴圈將用它檢查其餘的值。如果存在多個值,則只打印一個。

示例

此程式碼展示了我們解決方案的實現,

 即時演示

#include <iostream>
using namespace std;
void printDistinctValues(int arr[], int n) {
   for (int i=0; i<n; i++){
      int j;
      for (j=0; j<i; j++)
      if (arr[i] == arr[j])
         break;
      if (i == j)
         cout<<arr[i]<<"\t";
   }
}
int main(){
   int arr[] = {1, 5, 7, 12, 1, 6, 10, 7, 5};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"Distinct values of the array are :\n";
   printDistinctValues(arr, n);
   return 0;
}

輸出

Distinct elements of the array are −
1 5 6 7 10 12

此解決方案簡單易懂,但使用了兩個迴圈,這使得其複雜度為 n2 階。

另一種更復雜的方法是使用排序。在排序後的陣列中,相似數字的出現會變得連續。現在,我們可以輕鬆地列印不同的元素,並且它佔用的空間更少。

示例

我們邏輯的實現 -

 即時演示

#include <bits/stdc++.h>
using namespace std;
void printDistinctElements(int arr[], int n){
   sort(arr, arr + n);
   for (int i=0; i<n; i++){
      while (i < n-1 && arr[i] == arr[i+1])
         i++;
      cout<<arr[i]<<"\t";
   }
}
int main(){
   int arr[] = {1, 5, 7, 12, 1, 6, 10, 7, 5};
   int n = sizeof(arr)/sizeof(arr[0]);
   cout<<"Distinct elements of the array are :\n";
   printDistinctElements(arr, n);
   return 0;
}

輸出

Distinct elements of the array are −
1 5 6 7 10 12

另一種更有效的解決方案是跟蹤陣列中已訪問的元素。我們將遍歷陣列並跟蹤陣列中所有已訪問的元素。

示例

此程式碼展示了我們解決方案的實現,

 即時演示

#include<bits/stdc++.h>
using namespace std;
void printDistinctElements(int arr[],int n) {
   unordered_set<int> visited;
   for (int i=0; i<n; i++){
      if (visited.find(arr[i])==visited.end()){
         visited.insert(arr[i]);
         cout<<arr[i]<<"\t";
      }
   }
}
int main () {
   int arr[] = {1, 5, 7, 12, 1, 6, 10, 7, 5};
   int n=7;
   cout<<"Distinct numbers of the array are :\n";
   printDistinctElements(arr,n);
   return 0;
}

輸出

Distinct numbers of the array are −
1 5 7 12 6 10

更新於: 2020-01-22

705 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告