使用库实现,可以稍微加快速度。使用自定义集合可能会更快,但这超出了这里的范围。您正在遇到某些迭代限制,因此无论如何您只能做这么多。
将过程分解成更小的方法会很有帮助:
public static void decrementColumns(List<List<Integer>> rows, List<Boolean> mask) {
final List<Integer> maskIndicies = getMaskIndicies(mask);
// We're locked into this iteration because we have to modify every row.
for (List<Integer> row : rows) {
apply(maskIndicies, row);
}
}
// Your big savings will come from figuring out the indicies.
// This allows us to make the iterations-per-row smaller -
// assuming not every row (or even most) is set to 'true'!
public static List<Integer> getMaskIndicies(List<Boolean> mask) {
final List<Integer> maskIndicies = new ArrayList<Integer>(mask.size());
for (int i = 0; i < mask.size(); i++) {
if (mask.get(i)) {
maskIndicies.add(i);
}
}
}
public static void apply(List<Integer> maskIndicies, List<Integer> row) {
// We're locked into this iteration, needing to apply the transformation
// to every column included.
for (Integer index : maskIndicies) {
final Integer modified = row.get(index) - 1;
row.set(index, modified);
}
}
请注意,这不是线程安全的,所以要小心。我也没有写任何安全检查,所以...
编辑:
重新阅读该问题后,我意识到我最初误读了代码在做什么(而且我在踢自己 - 不知何故我掉了一个循环)。
修改后的版本:
public static void decrementColumns(List<List<Integer>> rows, List<Boolean> mask) {
final int count = getMaskCount(mask);
// We're locked into this iteration because we have to modify every row.
for (List<Integer> row : rows) {
apply(row, count);
}
}
public static void int getMaskCount(List<Boolean> mask) {
int count = 0;
for(Boolean flag : mask) {
if (!flag) {
count++;
}
}
return count;
}
public static void apply(List<Integer> row, int count) {
for (int index = 0; index < row.size(); index++) {
final Integer modified = row.get(index) - count;
row.set(index, modified);
}
}
请注意,这个仍然并没有做〜完全〜你的原始代码所做的,只是我假设你正在尝试做的事情,给定你的“要求”文本。一方面,您至少定义了 2 个附加列表,但您没有给出关系 - 我相当肯定其中一个是错字。如果您为了清楚起见而编辑您的问题,我可能会提供更好的答案;您的代码和问题文本之间存在一些模棱两可或矛盾的事情。请注意,虽然您的原始代码在 O(m * (n ^ 2)) 中运行,但最低限度(和我的版本)在 O(n + (m * n)) 中运行。