【发布时间】:2021-10-20 11:46:35
【问题描述】:
当我检查子序列时,我总是在循环之后复制条件。
例如,我想找到相差不超过一的数字的最大子序列。这是我的代码
public static List<Integer> maxSubsequence(List<Integer> array) {
int ind = 0;
int bestInd = 0;
int cnt = 1;
int maxCnt = 0;
for(int i = 1; i < array.size(); i++) {
if(Math.abs(array.get(ind) - array.get(i)) <= 1) {
cnt++;
continue;
}
if(cnt > maxCnt) {
bestInd = ind;
maxCnt = cnt;
}
if(Math.abs(array.get(ind) - array.get(i)) == 2) {
cnt--;
ind++;
i--;
} else {
cnt = 1;
ind = i;
}
}
// duplicate from loop
if(cnt > maxCnt) {
bestInd = ind;
maxCnt = cnt;
}
return array.subList(bestInd, bestInd + maxCnt);
}
for sequence 5, 1, 2, 3, 3, 3 answer is 2, 3, 3, 3
我正在复制条件,因为如果序列以匹配的子序列结尾,那么如果没有附加条件,它将不会被计算在内。我想避免代码重复。
我的解决方案需要更改输入。有什么方法可以在不改变输入的情况下避免代码重复。
将代码从条件转移到函数的解决方案不适合,因为它没有消除重复,我仍然需要调用函数两次。
【问题讨论】:
-
为什么你的例子中的答案不是 2,3,3,3?
-
@JoachimIsaksson 这是一个错误。修复。输出真的应该是
2, 3, 3, 3。
标签: java code-duplication