Quantcast
Channel: DaniWeb Solved Topics
Viewing all articles
Browse latest Browse all 587

Display minimum value that is not in array

$
0
0

Question from codility test

Write a function:

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

that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5.

Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.

Write an efficient algorithm for the following assumptions:

N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−1,000,000..1,000,000].

This is what I have tried

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

        int minValue = A[0];

        do {
            for (int i = 0; i < A.length; i++) {
                if (A[i] < minValue) {
                    minValue = A[i];
                }
            }
        } while (contains(A, ++minValue) == true);

        return minValue;
    }

    public static boolean contains(int[] arr, int item) {
        for (int n : arr) {
            if (item == n) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        int[] intArray = new int[]{1, 3, 6, 4, 1, 2};
        int ans = s.solution(intArray);
        System.out.println(ans);
    }
}

I get infinity loop, no result displayed.
Can someone please point me out what is wrong here ?


Viewing all articles
Browse latest Browse all 587

Trending Articles