Issue
I have an array which carry some integer numbers. Say,numbers={3,0,1}
or say, numbers={9,6,4,2,3,5,7,0,1}
. Now I have to find out the missing numbers from the array. As per this example there is only one missing number in each set. 1st one miss 2 and the 2nd one miss 8.
I have already code it. My code not only find out one missing number from specified set it can also find out more than 1 missing numbers from a given set.
But if two consecutive numbers are missing from same set it fail to find out.
My code
import java.util.Arrays;
public class Missing_number
{
public static void main( String args[] )
{
int numbers[]={9,6,4,5,7,0,1};
Arrays.sort(numbers);
int i=1;
while ( i < numbers.length )
{
if ( numbers[i] - numbers[i-1] == 1 )
{
}
else
{
System.out.println( "Missing number is " + ( numbers[i-1] + 1 ) );
}
i++;
}
}
}
I am thinking like that if I am able to append the 1st missing number in the array and then start searching then how's the code look like? numbers={9,6,4,5,7,0,1}
Now, 8 is already missing from this set. Now I have terminated two more element (2,3) from the list. Output: as per my code: 2,8 But 3 is also missing but that does not display.
I am thinking like if I am able to append 2 in number array then it may be little bit easier. But as we all know Java array is immutable so we cannot increase it's length.
So, maybe I will use List. But in list this type of indexing number[0]=something
not supported. So how could I proceed then. Am I using list or still stuck into array?
So I take a attempt to create it with an arraylist.
Mycode(modified version from array)
public class T1 {
public static void main(String args[]){
List<Integer> numbers=new ArrayList<>();
numbers.add(9);
numbers.add(6);
numbers.add(4);
numbers.add(5);
numbers.add(7);
numbers.add(0);
numbers.add(1);
Collections.sort(numbers);
int i=1;
while(i< numbers.size()) {
if (numbers.get(i) - numbers.get(i-1) == 1) {
} else {
System.out.println("Missing number is " + (numbers.get(i-1) + 1));
numbers.add((numbers.get(i-1)+1));
Collections.sort(numbers);
}
i++;
}
}
}
Arraylist can solve my problem. But is there any possibility that a simple array can solve this problem?
Solution
int[] numbers = { 11, 6, 4, 5, 7, 1 };
Arrays.sort(numbers);
int numbersArrayIndex = 0;
for (int i = 0; i < numbers[numbers.length - 1]; i++) {
if (i == numbers[numbersArrayIndex]) {
numbersArrayIndex++;
}
else {
System.out.println(i);
}
}
Answered By - stackUser
Answer Checked By - Gilberto Lyons (JavaFixing Admin)