-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOfficialAnswer.cs
44 lines (37 loc) · 1.22 KB
/
OfficialAnswer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// <copyright file="OfficialAnswer.cs" company="Ocean">
// Copyright (c) Ocean. All rights reserved.
// </copyright>
namespace Questions.LeetCode.No1.TwoSum
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The official answer of LeetCode No.1 question: Two Sum.
/// </summary>
public class OfficialAnswer : IQuestion
{
/// <inheritdoc />
public int[] TwoSum(int[] nums, int target)
{
// Step 0: Handles invalid or special cases.
if (nums == null || !nums.Any())
{
return Array.Empty<int>();
}
// Step 1: Handles normal cases.
var numDictionary = new Dictionary<int, int>();
for (var index = 0; index < nums.Length; index++)
{
var currentNumber = nums[index];
var currentGap = target - currentNumber;
if (numDictionary.ContainsKey(currentGap))
{
return new[] { index, numDictionary[currentGap] };
}
numDictionary.TryAdd(currentNumber, index);
}
return Array.Empty<int>();
}
}
}