| | 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.TwoSum; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class TwoSumDictionary : ITwoSum |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n) |
| | 19 | | /// Space complexity - O(n) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <param name="target"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int[] TwoSum(int[] nums, int target) |
| 4 | 25 | | { |
| 4 | 26 | | var dictionary = new Dictionary<int, int>(); |
| | 27 | |
|
| 20 | 28 | | for (var i = 0; i < nums.Length; i++) |
| 10 | 29 | | { |
| 10 | 30 | | var complement = target - nums[i]; |
| | 31 | |
|
| 10 | 32 | | if (dictionary.TryGetValue(complement, out var value)) |
| 4 | 33 | | { |
| 4 | 34 | | return [value, i]; |
| | 35 | | } |
| | 36 | |
|
| 6 | 37 | | if (!dictionary.ContainsKey(nums[i])) |
| 6 | 38 | | { |
| 6 | 39 | | dictionary[nums[i]] = i; |
| 6 | 40 | | } |
| 6 | 41 | | } |
| | 42 | |
|
| 0 | 43 | | return []; |
| 4 | 44 | | } |
| | 45 | | } |