java codility training Genomic-range-query

后端 未结 30 2257
悲哀的现实
悲哀的现实 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:49

    Java, 100/100, but with no cumulative/prefix sums! I stashed the last occurrence index of lower 3 nucelotides in a array "map". Later I check if the last index is between P-Q. If so it returns the nuclotide, if not found, it's the top one (T):

    class Solution {
    
    int[][] lastOccurrencesMap;
    
    public int[] solution(String S, int[] P, int[] Q) {
        int N = S.length();
        int M = P.length;
    
        int[] result = new int[M];
        lastOccurrencesMap = new int[3][N];
        int lastA = -1;
        int lastC = -1;
        int lastG = -1;
    
        for (int i = 0; i < N; i++) {
            char c = S.charAt(i);
    
            if (c == 'A') {
                lastA = i;
            } else if (c == 'C') {
                lastC = i;
            } else if (c == 'G') {
                lastG = i;
            }
    
            lastOccurrencesMap[0][i] = lastA;
            lastOccurrencesMap[1][i] = lastC;
            lastOccurrencesMap[2][i] = lastG;
        }
    
        for (int i = 0; i < M; i++) {
            int startIndex = P[i];
            int endIndex = Q[i];
    
            int minimum = 4;
            for (int n = 0; n < 3; n++) {
                int lastOccurence = getLastNucleotideOccurrence(startIndex, endIndex, n);
                if (lastOccurence != 0) {
                    minimum = n + 1; 
                    break;
                }
            }
    
            result[i] = minimum;
        }
        return result;
    }
    
    int getLastNucleotideOccurrence(int startIndex, int endIndex, int nucleotideIndex) {
        int[] lastOccurrences = lastOccurrencesMap[nucleotideIndex];
        int endValueLastOccurenceIndex = lastOccurrences[endIndex];
        if (endValueLastOccurenceIndex >= startIndex) {
            return nucleotideIndex + 1;
        } else {
            return 0;
        }
    }
    }
    

提交回复
热议问题