我正尝试重写我的代码。可以在我的代码中使用int[]
数组而不是Integer[]
吗?
当我用Integer[]
替换所有int[]
时,我陷入了替换的一部分:
.toArray(Integer[]::new);
使用
.toArray(int[]::new);
public class Main {
private static final int MODULO = (int) (Math.pow(10, 9) + 7);
private static int modulate(final long result) {
return (int) (result % MODULO);
}
//private static
private static Integer[] steps(final int smaller, final int larger) {
final int lcm = lowestCommonMultiple(smaller, larger);
final int max = lcm / smaller;
final int min = lcm / larger;
final Integer[] result = new Integer[max * 2];
int pos = 0;
for (int i = 1; i <= max; i++) {
result[pos++] = (i * smaller);
if (i <= min) {
result[pos++] = (i * larger);
}
}
return Arrays.stream(result)
.filter(Objects::nonNull)
.sorted()
.distinct()
.toArray(Integer[]::new);
}
private static long nthNonZeroMagicalNumber(final int N, final int smaller, final int larger) {
final Integer[] stepsInCycle = steps(smaller, larger);
final long lcm = stepsInCycle[stepsInCycle.length - 1];
final int inOneCycle = stepsInCycle.length;
final int fullCycleCount = N / inOneCycle;
int count = fullCycleCount * inOneCycle;
final long evaluated = fullCycleCount * lcm;
if (count == N) {
return evaluated;
}
final int remainder = N - count - 1;
return stepsInCycle[remainder] + evaluated;
}
private static int greatestCommonDenominator(int a, int b) {
while (b > 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
public static int lowestCommonMultiple(final int a, final int b) {
return a * (b / greatestCommonDenominator(a, b));
}
public static int nthMagicalNumber(final int N, final int A, final int B) {
if (N == 0) {
return 0;
} else if (A == B) {
final long result = (long) A * (long) N;
return modulate(result);
} else if (N == 1) {
return modulate(Math.min(A, B));
}
return modulate(nthNonZeroMagicalNumber(N, Math.min(A, B), Math.max(A, B)));
}
public static void main(String[] args) {
int result = nthMagicalNumber(53776, 22434, 31343);
}
}
如果有人可以给我任何建议,我将不胜感激。预先谢谢你!
答案 0 :(得分:3)
假设您以Integer[]
开始,则可以将流中的Integer拆箱,这将从您的IntStream
中获得Stream<Integer>
。
// if result is an Integer[]
return Arrays.stream(result)
.filter(Objects::nonNull)
.sorted()
.distinct()
.mapToInt(n -> n) // this gives an IntStream
.toArray(); // this returns an int[]
如果您实际上将result
数组更改为键入int[]
,则将不需要拆箱,但是您将无法再使用nonNull
过滤出元素:数组中未写入的元素将为零,而不是null。因此,您将拥有:
// if result is an int[]
return Arrays.stream(result)
.filter(n -> n!=0)
.sorted()
.distinct()
.toArray();
使用列表而不是数组可能会更好。列表可以根据需要增加大小,因此您不必跟踪到达的位置,也可以排除未写入的元素。