-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindMissingNumber.cs
More file actions
105 lines (97 loc) · 2.97 KB
/
FindMissingNumber.cs
File metadata and controls
105 lines (97 loc) · 2.97 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System;
using System.Collections.Generic;
namespace DA.Algorithms.Problems
{
public static class FindMissingNumber
{
/// <summary>
/// Find missing number in the array, which are in the range of 1 to n.
/// </summary>
///
/// <exception cref="System.InvalidOperationException" />
///
/// <param name="array">An array with integers, which are in the range of 1 to n.</param>
///
/// <returns>
/// Return a missed number.
/// </returns>
public static int Find (int[] array)
{
if (array[0] == 0)
{
throw new System.InvalidOperationException ("The array must be starting with value 1.");
}
bool isFound = false;
for (int i = 1; i <= array.Length; i++)
{
isFound = false;
for (int j = 0; j < array.Length; j++)
{
if (array[j] == i)
{
isFound = true;
break;
}
}
if (!isFound)
{
return i;
}
}
return int.MaxValue;
}
/// <summary>
/// Get missing numbers in the array, which are in the range of 0 to n-1.
/// </summary>
///
/// <exception cref="System.ArgumentNullException" />
///
/// <param name="array">An array with integers, which are in the range of 0 to n-1.</param>
///
/// <returns>
/// Return a List with missed numbers.
/// </returns>
public static List<int> FindNumbers (int[] array)
{
if (array == null)
{
throw new System.ArgumentNullException ();
}
bool isFound = false;
int maxValue = FindMax(array);
List<int> result = new List<int> ();
for (int currentNumber = 0; currentNumber <= maxValue; currentNumber++)
{
isFound = false;
for (int currentIndex = 0; currentIndex < array.Length; currentIndex++)
{
if (currentNumber == array[currentIndex])
{
isFound = true;
break;
}
}
if (!isFound)
{
result.Add (currentNumber);
}
}
return result;
}
/// <summary>
/// Find max value in the array.
/// </summary>
public static int FindMax (int[] array)
{
int maxValue = int.MinValue;
foreach (int number in array)
{
if (number > maxValue)
{
maxValue = number;
}
}
return maxValue;
}
}
}