-
Notifications
You must be signed in to change notification settings - Fork 7
/
Program.cs
74 lines (69 loc) · 1.86 KB
/
Program.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
namespace FindTheDuplicateNumber
{
class Program
{
static void Main(string[] args)
{
int[] nums = { 1, 3, 4, 2, 2 };
Console.WriteLine(FindDuplicate_BinarySearch(nums));
}
//Two points O(n)
static int FindDuplicate_FloydTortoiseHare(int[] nums)
{
int slow = nums[0];
int fast = nums[nums[0]];
while (fast != slow)
{
slow = nums[slow];
fast = nums[nums[fast]];
}
fast = 0;
while (fast != slow)
{
fast = nums[fast];
slow = nums[slow];
}
return fast;
}
static int FindDuplicate_Sort(int[] nums)
{
Array.Sort(nums);
for (int i = 1; i < nums.Length; i++)
{
if (nums[i] == nums[i - 1])
return nums[i];
}
return -1;
}
static int FindDuplicate_BinarySearch(int[] nums)
{
int li = 1, hi = nums.Length;
while (li < hi)
{
int mid = li + (hi - li) / 2;
int count = nums.Count(x => x <= mid);
if (count > mid)
hi = mid;
else
li = mid + 1;
}
return li;
}
static int FindDuplicate_HashTable(int[] nums)
{
var record = new HashSet<int>();
foreach (var num in nums)
{
if (record.Contains(num))
return num;
else
record.Add(num);
}
return -1;
}
}
}