Saved Bookmarks
| 1. |
Write a function to determine whether duplicate elements in a given array are within a given distance of each other. |
Answer»
public: bool checkDuplicatesWithinRange(vector<int> arr, int range) { // Creating an empty hashset unordered_set<int> myset; // Traversing the input array for (int i = 0; i < arr.size(); i++) { // If already present in hashset, then we found a duplicate within range distance if (myset.find(arr[i]) != myset.end()) return true; // Add this item to hashset myset.insert(arr[i]); // Remove the range+1 distant item from the hashset if (i >= range) myset.erase(arr[i-range]); } return false; } };
|
|