Write a function: int solution (int A [], int N);

0

My teacher gave me this problem but I can not do it

int solution(int A[], int N); 

which, given an A matrix of 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;
  • For another example, given A = [1, 2, 3] , the function should return 4;
  • Given A = [-1, -3] , the function should return 1;

Assume that:

  • N is an integer within the range [1..100,000];
  • Each element of matrix A is an integer within the range [-1,000,000 ... 1,000,000].

Elements of input matrices can be modified.

I tried using not in list , but I'm not able to formulate

a =(1, 3, 6, 4, 1, 2)
limite = max(a)

for i in a:
    if (i >=0 and i not in a and a <= limite):
        b = i;
        print(b)
    
asked by anonymous 08.06.2018 / 15:26

1 answer

0

To do this, simply start a variable, i , in 1, check if it is not in A ; if it is, return i , otherwise increment i and continue until the condition is true:

def solution(A, N) -> int:
    i = 1
    while True:
        if i not in A:
            return i
        i += 1

See working at Repl.it | Ideone | GitHub GIST

Alternatively, you can use the itertools.count function that already implements this logic:

from itertools import count

def solution(A, N) -> int:
    for i in count(1):
        if i not in A:
            return i

See working at Repl.it | Ideone | GitHub GIST

  

Note: Note that the N parameter is unnecessary for Python implementation, so I suspect the intent is to implement this in C - or another language.

    
08.06.2018 / 15:45