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

Asked

Viewed 1,008 times

-1

My teacher gave me this problem but I can’t do it

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

that, given a matrix A of N integers, returns the smallest positive integer (greater than 0) that does not occur on A.

For example,

  • Datum A = [1, 3, 6, 4, 1, 2], the function must return 5;
  • For another example, given A = [1, 2, 3], the function must return 4;
  • Datum A = [-1, -3], the function must return 1;

Assume that:

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

Input matrix elements can be modified.

I tried using the not in list, but I’m having trouble formulating

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)
  • But if you walk i in a, agrees that it makes no sense to check whether i not in a, since always i will be in a? By the way, are you sure this should be in Python? By the given header, it’s more like C.

  • Jeez, now that I realize that. will I get to do a tender operation?

1 answer

0

To do this, you just start a variable, i, in 1, check that she is not in A; if you are, return i, otherwise increase 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 on Repl.it | Ideone | Github GIST

Alternatively, you can use the function itertools.count 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 on Repl.it | Ideone | Github GIST

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.