solved

1
2
3
4
5
for (int i = 0; i < ARRAY_SIZE; i ++)
   for (int j = i + 1; j < ARRAY_SIZE; j ++)
      // number found
      if (myArray[i] == myArray[j])
         std::cout << "Duplicate number found: " << myArray[i];
This is what I came up with still running into some trouble

int main(){
int myArray[1000001];
//For Loop to check through the Array
for (int i = 1; i < 1000000; i++)
for (int j = i + 1; j < 1000000; j ++)
{
if (myArray[i] == myArray[j])
{
cout << "Duplicate number found: " << myArray[i];
break;
}
}

}
First off, you're creating an array size of 1,000,001. Why? The instructions only say the array will hold numbers 1-1,000,000. It doesn't say that it will be 1,000,000 values in that array.

Also, you're not including all possible choices. int i should start at 0, not 1. Also, what sort of trouble are you having?
Just realized that, must've slipped my mind so I tweaked my program and its working fine now..... Thanks for your help.
This looks like homework to me.

Apologies to Volatile Pulse - I am going to have a go here - hope you don't mind.
If it is homework, I doubt that it should be answered with 4 lines of code!!

The problem is that if the array size is 1 million, the nested for loops will run 1 trillion times. If you have a computer that can process 1 billion items per second on this data, then it will still take 1000 seconds to execute - which is 16 minutes 40 seconds - quite long don't you think.

Also if it is homework, I would have thought that the teacher would have given reasonable instructions on how to go about doing the assignment. I am sure there would have been more to it than a couple of for loops. I think the fact that the amount of data is 1 million was done on purpose, so it would force the students to use a decent data structure to hold the data, thereby giving a much better algorithm to find the answer.

So to the OP, can you come with a data structure to hold this info and make it easier to find the answer?

Are you allowed to use C++ STL containers, or do you have code the whole thing yourself?


Edit:

Your array doesn't have any data in it - Where is this coming from?
Last edited on
It's frowned upon to delete stuff out of your post like that.

If it's solved, just mark it as solved.

If you thought it was a silly question, then don't worry everyone starts somewhere!!
You should've keep your question even after it solved for other people to learn, man!
The original question was:
KingJ wrote:
Array Help
Given an array of integers between 1 and 1,000,000. One integer is in the array twice. How do I find the duplicate number??
Topic archived. No new replies allowed.