Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C 프로그램에서 배열의 마지막 요소를 상대적인 순서로 인쇄합니다.

<시간/>

요소가 있는 배열 a[]가 주어지고 작업은 목록에서 주어진 요소의 마지막 항목을 인쇄하는 것입니다. 여기서 중복 요소를 제거해야 할 뿐만 아니라 마지막으로 발생한 시간에 따라 배열에서 요소의 발생 순서를 유지해야 합니다.

중복 값(예:{1,3, 2, 3, 1, 2})도 포함하는 6개 요소의 배열이 있는 것처럼 결과는 3 1 2 형식이어야 합니다.

예시

Input: a[]={4,2,2,4,1,5,1}
Output : 2 4 5 1

C 프로그램에서 배열의 마지막 요소를 상대적인 순서로 인쇄합니다.

알고리즘

START
Step 1-> Declare function void printelements(int a[], int n)
   Use STL unordered_map<int, int> ele
   Loop For int i=0 and i<n and i++
      Set ele[a[i]]=i
   Loop For int i=0 and i<n and i++
      IF ele[a[i]]=i
         Print a[i]
      End
   End
Step 2 -> main()
   Declare array a[]={4,2,2,4,1,5,1}
   Declare int n=sizeof(a)/sizeof(a[0])
   Call Function printelements(a,n)
STOP

예시

#include <bits/stdc++.h>
using namespace std;
void printelements(int a[], int n) {
   unordered_map<int, int> ele;
   for (int i = 0; i < n; i++)
      ele[a[i]] = i;
   for (int i = 0; i < n; i++) {
      if (ele[a[i]] == i)
         cout << a[i] << " ";
   }
}
int main() {
   int a[] = { 4,2,2,4,1,5,1 };
   int n = sizeof(a) / sizeof(a[0]);
   printelements(a, n);
   return 0;
}

출력

위의 프로그램을 실행하면 다음 출력이 생성됩니다.

2 4 5 1