-
#include <iostream> /* Interview question 3: Repeating numbers in an array: Question: An array of length n, each element of size between 0 and n-1, find the repeated numbers in it Solution: 1. Sort O(nlogn) 2. Using a hash table, the hash function maps the key key to an array subscript o(n), space complexity (n) 3. When there are no duplicates and they are sorted, the subscript and value should be equal, so scan the array: When the value there is not in its place, put it where it should be When the value there is in its bit, scan the next element In a word: put a value that is no longer in its place where it should be */ using namespace std; const int MAX = 1000; int array_n[MAX]; int n; int main(void) { cin >> n; for (int i = 0; i < n; i++) cin >> array_n[i]; int i=0; bool find_duplicates = false; int duplicates = 0; while(true) { if(i == n) break; // when its bit, scan the next element if (array_n[i] == i) i++; else { // Check the duplicate before swapping positions if (array_n[array_n[i]] == array_n[i]) { find_duplicates = true; duplicates = array_n[i]; break; } else { // when not in its place, put it where it should be int temp = array_n[array_n[i]]; array_n[array_n[i]] = array_n[i]; array_n[i] = temp; } } } if (find_duplicates) cout << duplicates; else cout << "not find"; return 0; }
Interview question 3: Repeating numbers in an array
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=324537412&siteId=291194637
Recommended
Ranking