Tag: hash array element spacing array element distance element distance equals specified value
given an unordered array that contains multiple repeating elements. Also given a number k, and K is less than the array size. Determines whether the array contains duplicate elements, and the distance between them is within the range K.
For example:
Input:k = 3, arr[] = {1, 2, 3, 4, 1, 2, 3, 4}
Output:false
The distance of all the repeating elements is >k.
Input:k = 3, arr[] = {1, 2, 3, 1, 4, 5}
Output:true
There is a repeating element of 1, and the distance is 3 (==k).
Input:k = 3, arr[] = {1, 2, 3, 4, 5}
Output:false
No duplicate elements
Input:k = 3, arr[] = {1, 2, 3, 4, 4}
Output:true
Duplicate element 4 exists, and distance is 1 (<k)
Method 1 (Simple method)use two loops. The outer loop iterates through all the elements of the array arr[i], as the starting element, and the inner loop compares all elements in the K range with Arr[i] to detect equality. This method has a time complexity of O (k*n).
Method 2 (use hash) time complexity: Θ (n) Time
The whole idea is to add elements to the hash table. Then the element with the current element spacing greater than k is removed. The following is a concrete algorithm.
1) Creates an empty hash table.
2) traverses all elements from left to right. Assume that the current element is arr[i].
A) returns true if the current element ' Arr[i ' appears in the hash table.
B) Otherwise arr[i] is added to the hash table, and if I is greater than or equal to K, Arr[i-k] is removed from the hash table.
Code implementation:
#if __gnuc__>2#include <ext/hash_set> #include <ext/hash_map>using namespace __gnu_cxx; #else # include
output:
exist Duplicates
Hash (6)-Determines if duplicate elements are present in the array and the distance is within K