查詢整數陣列中第一個重複元素(C++)
在這個問題中,我們有一個包含 n 個整數值的陣列 arr。我們的任務是查詢整數陣列中第一個重複元素。
我們需要找到陣列中第一個出現不止一次的整數值。
讓我們舉個例子來理解這個問題,
Input : arr[] = {4, 1, 8, 9, 7, 2, 1, 6, 4} Output : 4
說明 −
Integers with more than one occurrence are 4 and 1. 4's first occurrence is smaller than 1. Hence the answer is 4
解決方案方法
解決這個問題的一個簡單方法是使用巢狀迴圈。我們將使用兩個迴圈,外部迴圈迭代陣列的每個整數值,內部迴圈檢查陣列中是否存在另一個具有相同值的整數值。如果是,則返回該值。這種方法很好,但在沒有解決方案的情況下,其複雜度將為 O(N2)。
解決方案方法
另一種可以更好地解決問題的方案是使用雜湊表。我們將從最後一個索引遍歷陣列,然後更新在訪問的索引處找到的元素的最小索引。
示例
程式說明解決方案的工作原理
#include<bits/stdc++.h> using namespace std; int findRepeatingElementArray(int arr[], int n){ int minRetIndex = -1; set<int> visitedElements; for (int i = n - 1; i >= 0; i--){ if (visitedElements.find(arr[i]) != visitedElements.end()) minRetIndex = i; else visitedElements.insert(arr[i]); } if (minRetIndex != -1) return arr[minRetIndex]; else return -1; } int main(){ int arr[] = {4, 1, 6, 3, 4, 1, 5, 8}; int n = sizeof(arr) / sizeof(arr[0]); cout<<"The element with repeated occurence is "<<findRepeatingElementArray(arr, n); }
輸出
The element with repeated occurence is 4
廣告