Hash (6)-Determines if duplicate elements are present in the array and the distance is within K

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.