This is a rather simple data structures question, especially for this kind of. In this case you can simply add all numbers stored in array, and total sum should be equal to n(n+1)/2. Now just subtract actual sum to expected sum, and that is your duplicate number. Of course there is a brute force way of checking each number against all other numbers, but that will result in performance of O(n^2) which is not good. By the way this trick will not work if array have multiple duplicates or its not numbers forming arithmetic progression.

Method 1:

1 2 3 4 5 6 7 8 9 10 11 12 13 |
int[] arrInteger = {1,2,3,4,5,6,7,8,9,1,2 }; List<int> arrTemp = new List<int>(); foreach (int i in arrInteger) { if (!arrTemp.Contains(i)) { arrTemp.Add(i); } else { Console.WriteLine("duplicate number :"+i.ToString()); } } |

Method 2:

1 2 3 4 5 6 7 8 9 10 11 12 13 |
int[] arrInteger = {1,2,3,4,5,6,7,8,9,1,2,3,4,5,7 }; int intPre = arrInteger[0]; Array.Sort(arrInteger); for(int i=1;i<arrInteger.Length;i++) { if (intPre==arrInteger[i]) { Console.WriteLine("duplicate number :" + arrInteger[i].ToString()); } intPre = arrInteger[i]; } Console.ReadLine(); |