From 0be3f9239660eb0cd625fad3ad2c256315bf5209 Mon Sep 17 00:00:00 2001 From: Jidong Xiao Date: Fri, 28 Feb 2025 13:48:55 -0500 Subject: [PATCH] adding the cpp file --- lectures/15_maps_I/README.md | 4 +- .../15_maps_I/containsNearbyDuplicate.cpp | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 lectures/15_maps_I/containsNearbyDuplicate.cpp diff --git a/lectures/15_maps_I/README.md b/lectures/15_maps_I/README.md index 7f11dc4..7701ecf 100644 --- a/lectures/15_maps_I/README.md +++ b/lectures/15_maps_I/README.md @@ -174,7 +174,7 @@ on whether or not the key was in a pair in the map. Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k. -We have the solution below, and the cpp file is also here: [containsNearbyDuplicate.cpp](containsNearbyDuplicate.cpp) +We have the solution below. ```cpp #include @@ -230,7 +230,7 @@ Test Case 5: true Test Case 6: false ``` -You can also find the problem here: +You can also find this problem on Leetcode. - [Leetcode problem 219: Contains Duplicate II](https://leetcode.com/problems/contains-duplicate-ii/description/). Solution: [p219_contains_duplicate_ii.cpp](../../leetcode/p219_contains_duplicate_ii.cpp). ## 15.11 More Leetcode Exercises diff --git a/lectures/15_maps_I/containsNearbyDuplicate.cpp b/lectures/15_maps_I/containsNearbyDuplicate.cpp new file mode 100644 index 0000000..a225a58 --- /dev/null +++ b/lectures/15_maps_I/containsNearbyDuplicate.cpp @@ -0,0 +1,40 @@ +#include +#include +#include + +bool containsNearbyDuplicate(std::vector& nums, int k) { + int size = nums.size(); + // create the map, map key is the value of the vector element, map value is the index of that element in the vector. + std::map map1; + for(int i=0;i> testCases = { + {1, 2, 3, 1}, // Expected: true (nums[0] == nums[3], abs(0-3) <= k) + {1, 0, 1, 1}, // Expected: true (nums[2] == nums[3], abs(2-3) <= k) + {1, 2, 3, 4, 5}, // Expected: false (no duplicates) + {1, 2, 3, 4, 1}, // Expected: true if k >= 4 + {99, 99}, // Expected: true if k >= 1 + {1, 2, 3, 4, 5, 6}, // Expected: false (no duplicates) + }; + + std::vector kValues = {3, 1, 2, 4, 1, 2}; // Corresponding k values for test cases + + for (size_t i = 0; i < testCases.size(); i++) { + std::cout << "Test Case " << i + 1 << ": "; + bool result = containsNearbyDuplicate(testCases[i], kValues[i]); + std::cout << (result ? "true" : "false") << std::endl; + } + + return 0; +}