Tom - 10 months ago 71

Java Question

I am trying to solve the codility MissingInteger problem link:

`Write a function:`

class Solution { public int solution(int[] A); }

that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer that does not occur in A.

For example, given:

A[0] = 1

A[1] = 3

A[2] = 6

A[3] = 4

A[4] = 1

A[5] = 2

the function should return 5.

Assume that:

N is an integer within the range [1..100,000];

each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].

Complexity:

expected worst-case time complexity is O(N);

expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.

My solution is:

`class Solution {`

TreeMap<Integer,Object> all = new TreeMap<Integer,Object>();

public int solution(int[] A) {

for(int i=0; i<A.length; i++)

all.put(i+1,new Object());

for(int i=0; i<A.length; i++)

if(all.containsKey(A[i]))

all.remove(A[i]);

Iterator notOccur = all.keySet().iterator();

if(notOccur.hasNext())

return (int)notOccur.next();

return 1;

}

}

The test result is:

Can anyone explain me why I got this two wrong answers? Especially the first one, if there is only one element in the array, shouldn't the only right answer be 1?

Answer

returns the minimal positive integer that does not occur in A.

So in an array with only one element, if that number is 1, you should return 2. If not, you should return 1.

I think you're probably misunderstanding the requirements a little. Your code is creating keys in a map based on the *indexes* of the given array, and then removing keys based on the *values* it finds there. This problem shouldn't have anything to do with the array's indexes: it should simply return the lowest possible positive integer that isn't a value in the given array.

So, for example, if you iterate from `1`

to `Integer.MAX_VALUE`

, inclusive, and return the first value that isn't in the given array, that would produce the correct answers. You'll need to figure out what data structures to use, to ensure that your solution scales at `O(n)`

.