-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathContainsDuplicate.cs
54 lines (51 loc) · 1.75 KB
/
ContainsDuplicate.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
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCodeSolutionsLib
{
/// <summary>
/// 217. Contains Duplicates
/// Given an array of integers, find if the array contains any duplicates.
/// IE) Input: [1,2,3,1]
/// Output: true
/// </summary>
public class ContainsDuplicate : Solution
{
private int[] _nums;
public ContainsDuplicate(int[] nums)
{
this._nums = nums;
}
private bool containsDuplicates(int[] nums)
{
// If array is empty or only has 1 value, it is not a duplicate
if (nums.Length <= 1)
{
return false;
}
HashSet<int> hashset = new HashSet<int>();
for (int i = 0; i <= nums.Length - 1; i++)
{
// Check if current number can be added to the hashSet
// If hashSet.Add == false, then there is a duplicate found.
if (!hashset.Add(nums[i]))
{
return true;
}
hashset.Add(nums[i]);
}
Console.WriteLine($"Hashset count: {hashset.Count} NumsArr length: {nums.Length}");
return false;
}
public override void PrintExample()
{
var watch = System.Diagnostics.Stopwatch.StartNew();
var result = containsDuplicates(this._nums);
watch.Stop();
Console.WriteLine($"217. Contains Duplicates\n" +
$"Input Array = {this.printInputArray(this._nums)} \n" +
$"Result: [{result}] \n" +
$"Execution Speed: {watch.ElapsedMilliseconds}ms \n");
}
}
}