【发布时间】:2013-10-23 21:35:28
【问题描述】:
任务是:
给出了一个非空的零索引字符串 S。字符串 S 由大写英文字母 A、C、G、T 集合中的 N 个字符组成。
这个字符串实际上代表一个DNA序列,大写字母代表单个核苷酸。
你还得到了由 M 个整数组成的非空零索引数组 P 和 Q。这些数组代表关于最小核苷酸的查询。我们将字符串 S 的字母表示为数组 P 和 Q 中的整数 1、2、3、4,其中 A = 1、C = 2、G = 3、T = 4,我们假设 A
查询 K 要求您从 (P[K], Q[K]) 0 ≤ P[i] ≤ Q[i]
例如,考虑字符串 S = GACACCATA 和数组 P、Q,这样:
P[0] = 0 Q[0] = 8
P[1] = 0 Q[1] = 2
P[2] = 4 Q[2] = 5
P[3] = 7 Q[3] = 7
这些范围内的最少核苷酸如下:
(0, 8) is A identified by 1,
(0, 2) is A identified by 1,
(4, 5) is C identified by 2,
(7, 7) is T identified by 4.
写一个函数:
class Solution { public int[] solution(String S, int[] P, int[] Q); }
给定一个由 N 个字符组成的非空零索引字符串 S 和两个由 M 个整数组成的非空零索引数组 P 和 Q,返回一个由 M 个字符组成的数组,指定所有查询的连续答案.
序列应返回为:
a Results structure (in C), or
a vector of integers (in C++), or
a Results record (in Pascal), or
an array of integers (in any other programming language).
例如,给定字符串 S = GACACCATA 和数组 P、Q,这样:
P[0] = 0 Q[0] = 8
P[1] = 0 Q[1] = 2
P[2] = 4 Q[2] = 5
P[3] = 7 Q[3] = 7
该函数应返回值 [1, 1, 2, 4],如上所述。
假设:
N is an integer within the range [1..100,000];
M is an integer within the range [1..50,000];
each element of array P, Q is an integer within the range [0..N − 1];
P[i] ≤ Q[i];
string S consists only of upper-case English letters A, C, G, T.
复杂性:
expected worst-case time complexity is O(N+M);
expected worst-case space complexity is O(N),
beyond input storage
(not counting the storage required for input arguments).
输入数组的元素可以修改。
我的解决方案是:
class Solution {
public int[] solution(String S, int[] P, int[] Q) {
final char c[] = S.toCharArray();
final int answer[] = new int[P.length];
int tempAnswer;
char tempC;
for (int iii = 0; iii < P.length; iii++) {
tempAnswer = 4;
for (int zzz = P[iii]; zzz <= Q[iii]; zzz++) {
tempC = c[zzz];
if (tempC == 'A') {
tempAnswer = 1;
break;
} else if (tempC == 'C') {
if (tempAnswer > 2) {
tempAnswer = 2;
}
} else if (tempC == 'G') {
if (tempAnswer > 3) {
tempAnswer = 3;
}
}
}
answer[iii] = tempAnswer;
}
return answer;
}
}
这不是最佳的,我相信它应该在一个循环内完成,任何提示我该如何实现它?
您可以在这里检查解决方案的质量https://codility.com/train/ 测试名称是 Genomic-range-query。
【问题讨论】:
-
这可能不是这个问题的正确位置。试试Codereview。
-
供将来参考,此问题称为Range Minimum Query,如您的回答所示,您可以在 O(1) 中处理范围查询,给定 O(N) 预处理。