6. Get the positive smallest number that is missing in array
Tool
-Java 8-CoderPad/sanbox
Solution
import java.io.*;
import java.util.*;
import static java.util.Comparator.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class Solution
{
public static void main(String[] args)
{
import java.util.*;
import static java.util.Comparator.*;
/*
* To execute Java, please define "static void main" on a class
* named Solution.
*
* If you need more classes, simply define them inline.
*/
class Solution
{
public static void main(String[] args)
{
//Init array 1
List <Integer>array = new ArrayList<Integer>();
array.add(3);
array.add(4);
array.add(-1);
array.add(1);
List <Integer>array = new ArrayList<Integer>();
array.add(3);
array.add(4);
array.add(-1);
array.add(1);
//Get the smallest num that is missing in array
int res = getMin(array);
int res = getMin(array);
//Print result
System.out.println("The smallest number that is missing in array is "+res);
// Init array 2
List <Integer>array2 = new ArrayList<Integer>();
array2.add(1);
array2.add(2);
array2.add(0);
System.out.println("The smallest number that is missing in array is "+res);
// Init array 2
List <Integer>array2 = new ArrayList<Integer>();
array2.add(1);
array2.add(2);
array2.add(0);
// Get the smallest num that is missing in array 2
int res2 = getMin(array2);
int res2 = getMin(array2);
//Print result
System.out.println("Min number that lefts in array 2 is "+res2);
}
public static int getMin(List<Integer>array)
{
System.out.println("Min number that lefts in array 2 is "+res2);
}
public static int getMin(List<Integer>array)
{
//Sort the array that identify faster the smallest num
array.sort(Integer::compareTo);
int res =0;
for(int x=0; x<array.size();x++)
{
array.sort(Integer::compareTo);
int res =0;
for(int x=0; x<array.size();x++)
{
//check if next element exists
if(x+1 < array.size())
{
if(x+1 < array.size())
{
//aux is equals to the current element plus one. This will help to identify the missing number
int aux = array.get(x)+1;
int aux = array.get(x)+1;
//if aux is less than the next element in array and aux is diferent to 0. Then a element is missing in array
if(array.get(x+1)> aux && aux >0)
{
if(array.get(x+1)> aux && aux >0)
{
//Res is equeal to the current element in array plus 1 which means that the next number must be the current element plus one
res =array.get(x)+1;
break;
}
}
}
res =array.get(x)+1;
break;
}
}
}
//If res is equeal to 0 then the smallest number than is missing in array is the last number in array plus 1
if(res ==0)
res = array.get(array.size()-1)+1;
return res;
}
}
if(res ==0)
res = array.get(array.size()-1)+1;
return res;
}
}