+ 3

No duplication of numbers in array??

when you enter the elements in array it should not accept the duplicate numbers in array.

27th Oct 2017, 1:27 PM
Pritish
Pritish - avatar
2 odpowiedzi
+ 8
If you are filling the array one by one, you can create a method called: boolean hasDuplicate(int[] array, int item). Which would return true if the item is already in the array, therefore if that is true you do not add it in. This can be done with a single for loop, just checking each element to see if that element is in it. (If the array is sorted you could do a binary search instead). Or, If you already have the array filled, and are not filling it then you may have to manually search each element. 2 loops will be required. Start at the first element, check if its equal to anything from the next element to the end of the array. And so on. If it is equal, then remove the duplicate item. Or, If you don't want to go through the hastle of writing some algorithm, you can use a Set instead of an array. Sets do not allow duplicate items based on their hashcode() and equals() method. Although, this means you will need to use Integer's instead of int's.
27th Oct 2017, 3:37 PM
Rrestoring faith
Rrestoring faith - avatar
27th Oct 2017, 3:40 PM
shobhit
shobhit - avatar