array issue
-
The issue is: You are given an array of integers of size n containing values in the range 1 to n-1. Obviously there’s at least one duplicate value in this array. Please let me know the algorithm for finding one such duplicate value. Thanks.
There are many ways you can go about doing this. There are a few questions you should look at first though. Is the array sorted? Can you define another data structure? Are you trying to keep the complexity below a certain level? I might do something like the following:
for (int iSize = 0; iSize < yourArray.Count; iSize++) { while (yourArray[iSize] != iSize) { if (yourArray[iSize] == yourArray[yourArray[iSize]]) { MessageBox.Show( "Duplicate value of " + yourArray[iSize].ToString() ); iSize = yourArray.Count; break; } Swap(yourArray[iSize], yourArray[yourArray[iSize]]); } }
I didn't really test this, just pulled it off the top of my head real quick. It might work, but I can't give any guarantees. Good luck