java codility training Genomic-range-query

后端 未结 30 2325
悲哀的现实
悲哀的现实 2021-02-01 12:47

The task is:

A non-empty zero-indexed string S is given. String S consists of N characters from the set of upper-case English letters A, C, G, T.

<
30条回答
  •  一个人的身影
    2021-02-01 13:34

    Python Solution with explanation

    The idea is to hold an auxiliary array per nucleotide X, with position i (ignoring zero) is how many times X has occurred as of now. And so if we need the number of occurrences of X from position f to position t, we could take the following equation:

    aux(t) - aux(f)

    Time complexity is:

    O(N+M)

    def solution(S, P, Q):
        n = len(S)
        m = len(P)
    
        aux = [[0 for i in range(n+1)] for i in [0,1,2]]
    
        for i,c in enumerate(S):
            aux[0][i+1] = aux[0][i] + ( c == 'A' )
            aux[1][i+1] = aux[1][i] + ( c == 'C' )
            aux[2][i+1] = aux[2][i] + ( c == 'G' )
    
        result = []
    
        for i in range(m):
            fromIndex , toIndex = P[i] , Q[i] +1
            if   aux[0][toIndex] - aux[0][fromIndex] > 0:
                r = 1
            elif aux[1][toIndex] - aux[1][fromIndex] > 0:
                r = 2
            elif aux[2][toIndex] - aux[2][fromIndex] > 0:
                r = 3
            else:
                r = 4
    
            result.append(r)
    
        return result
    

提交回复
热议问题