| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.ContainsDuplicate3; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class ContainsDuplicate3Dictionary : IContainsDuplicate3 |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(min(n, k)),where k is the maximum number of elements the dictionary can hold at any one |
| | 20 | | /// based on the indexDiff |
| | 21 | | /// </summary> |
| | 22 | | /// <param name="nums"></param> |
| | 23 | | /// <param name="indexDiff"></param> |
| | 24 | | /// <param name="valueDiff"></param> |
| | 25 | | /// <returns></returns> |
| | 26 | | public bool ContainsNearbyAlmostDuplicate(int[] nums, int indexDiff, int valueDiff) |
| 9 | 27 | | { |
| 9 | 28 | | if (indexDiff <= 0 || valueDiff < 0) |
| 2 | 29 | | { |
| 2 | 30 | | return false; |
| | 31 | | } |
| | 32 | |
|
| 7 | 33 | | var numsDictionary = new Dictionary<long, long>(); |
| | 34 | |
|
| 7 | 35 | | var w = (long)valueDiff + 1; |
| | 36 | |
|
| 60 | 37 | | for (var i = 0; i < nums.Length; i++) |
| 26 | 38 | | { |
| 26 | 39 | | var m = GetId(nums[i], w); |
| | 40 | |
|
| 26 | 41 | | if (numsDictionary.ContainsKey(m) || |
| 26 | 42 | | (numsDictionary.ContainsKey(m - 1) && Math.Abs(nums[i] - numsDictionary[m - 1]) < w) || |
| 26 | 43 | | (numsDictionary.ContainsKey(m + 1) && Math.Abs(nums[i] - numsDictionary[m + 1]) < w)) |
| 3 | 44 | | { |
| 3 | 45 | | return true; |
| | 46 | | } |
| | 47 | |
|
| 23 | 48 | | if (i >= indexDiff) |
| 13 | 49 | | { |
| 13 | 50 | | var oldBucket = GetId(nums[i - indexDiff], w); |
| | 51 | |
|
| 13 | 52 | | numsDictionary.Remove(oldBucket); |
| 13 | 53 | | } |
| | 54 | |
|
| 23 | 55 | | numsDictionary[m] = nums[i]; |
| 23 | 56 | | } |
| | 57 | |
|
| 4 | 58 | | return false; |
| 9 | 59 | | } |
| | 60 | |
|
| | 61 | | private static long GetId(long x, long w) |
| 39 | 62 | | { |
| 39 | 63 | | return x < 0 ? ((x + 1) / w) - 1 : x / w; |
| 39 | 64 | | } |
| | 65 | | } |