กำหนดอาร์เรย์ a[] พร้อมองค์ประกอบและงานคือการพิมพ์การเกิดขึ้นล่าสุดขององค์ประกอบที่กำหนดในรายการ ที่นี่เราไม่เพียงแต่ต้องลบองค์ประกอบที่ซ้ำกันเท่านั้น แต่ยังต้องรักษาลำดับการเกิดขึ้นขององค์ประกอบในอาร์เรย์ตามครั้งสุดท้ายที่เกิดขึ้น
เช่นเดียวกับที่เรามีอาร์เรย์ 6 องค์ประกอบที่มีค่าที่ซ้ำกัน เช่น {1,3, 2, 3, 1, 2} ดังนั้นผลลัพธ์ควรอยู่ในรูปแบบ 3 1 2
ตัวอย่าง
Input: a[]={4,2,2,4,1,5,1}
Output : 2 4 5 1

อัลกอริทึม
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