이 문제에서는 정수 값의 배열이 제공됩니다. 우리의 임무는 배열의 모든 개별 요소를 인쇄하는 것입니다. 출력에는 고유한 값만 포함되어야 합니다.
문제를 이해하기 위해 예를 들어보겠습니다.
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