라이브러리 구현을 사용하면이 속도가 약간 빨라질 수 있습니다. 맞춤 컬렉션을 사용하면 일 수도 있고 일 수도 있습니다.하지만이 범위는 여기에서 벗어납니다. 은 특정 반복 제약 조건에 비해 최대이므로 모든 경우에 할 수있는 일은 많습니다.
이 작은 방법으로 절차를 중단하는 것이 도움이 될 것입니다 :
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);
}
}
이 여전히이 수행되지 않도록 유의하시기 바랍니다 ~ 꼭 ~ 원래 코드가 무엇을, 당신이 시도하는 경우에만 제가 있으리라 믿고있어, 주어진 당신의 '요구 사항'텍스트 우선, 적어도 추가 목록을 정의하십시오. 관계를 제공하지 않는 것이 좋습니다. 그 중 하나는 오타입니다. 명확하게 질문을 편집하면 더 나은 대답을 드릴 수 있습니다. 코드와 질문 텍스트 사이에 모호하거나 모순되는 점이 몇 가지 있습니다. 원래 코드가 O(m * (n^2))
에서 실행되는 동안 최소 및 내 버전은 O(n + (m * n))
에서 실행됩니다.
내 방식대로하는 것에 대한 제안 사항 (즉, 약간 증가하지 않았습니까?) 나는이 논리를 정말로 떨어 뜨리고 싶다. –