Finding the smallest integer that is not in the array

Given an unsorted collection A , what is the most efficient solution for finding the smallest integer x that is not an element of A , so that x must be larger than some integer m ?

eg.

Input: A = {7, 3, 4, 1} , m = 5

Output: x = 6

I am looking for a solution in C, but any pseudo code would be useful ... Can this problem be solved in O (n), where n is the given size?

+6
source share
3 answers

I decided to use it and an additional array. Here "len" is the length of the array.

 int findMin(int *arr,int n,int len) { int *hash; if(len==0) {return -1; //fail } hash=(int*)calloc(len,sizeof(int)); //hash function I'm using is f(x)=f(x)-n; int i; for(i=0;i<len;i++){ if(arr[i]>n && arr[i]<len+n){ //because max element can't be more than n hash[arr[i]-n]++; } } i=1; while(i<len){ if(hash[i]==0) return len+i; i++; } return len+n+1; } 

The order of this soul is the operating hours of O (n) and O (n).

+5
source

The following Java code should work for you:

 public static int findMinNotInArray(int array[], int n) { int frequency[] = new int[array.length]; if (n < max(array)) { for (int i = 0; i < array.length; i++) { if (array[i] > n && array[i] < n + array.length) frequency[array[i] - (n + 1)]++; } for (int i = 0; i < frequency.length; i++) { if (frequency[i] == 0) return i + n + 1; } return -1; } else { return n + 1; } } public static int max(int array[]) { int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } 

The above code just keeps track of numbers from n+1 to (n+1) + lengthOfA whether any of this range is present in the array or not! And returns the first unsuitable number!

+3
source

I think the most suitable approach is to sort the array first. Then you can perform a binary search for m in it, followed by a linear search for the next point where the neighbors are more than once.

The complexity of this approach lies in the fact that the sorting algorithm, that is, O (nlogn) in most cases.

+1
source

Source: https://habr.com/ru/post/948422/


All Articles