ในปัญหานี้ เราได้รับอาร์เรย์ของค่าจำนวนเต็ม งานของเราคือพิมพ์องค์ประกอบที่แตกต่างกันทั้งหมดของอาร์เรย์ ผลลัพธ์ควรมีเฉพาะค่าที่แตกต่างกันเท่านั้น
มาดูตัวอย่างทำความเข้าใจปัญหากัน
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
วิธีแก้ปัญหานี้ง่าย แต่ใช้สองลูปซึ่งทำให้ความซับซ้อนของลำดับของ n 2 .
วิธีที่ซับซ้อนกว่านี้คือการใช้การเรียงลำดับ ในอาร์เรย์ที่เรียงลำดับ การเกิดขึ้นของตัวเลขที่คล้ายกันจะกลายเป็นแบบต่อเนื่องกัน ตอนนี้ เราสามารถพิมพ์องค์ประกอบที่แตกต่างได้อย่างง่ายดายและใช้พื้นที่น้อยลง
ตัวอย่าง
การดำเนินการตามตรรกะของเรา -
#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