【发布时间】:2020-09-15 16:51:16
【问题描述】:
我在 leetcode 上提交了最大子数组问题的解决方案后,它说我的运行时间是 1 毫秒(超过了约 66% 的提交),然后我做了一些更改并重新提交。这一次,运行时间为 0 毫秒(超过 ~100%)。我不太明白是什么导致了时间的减少。这是两个版本。
原文:
public int maxSubArray(int[] nums) {
if (nums == null) return 0;
if (nums.length == 1) return nums[0];
int current_max = nums[0];
int cur = 1;
int max = current_max;
while (cur < nums.length) {
current_max = Math.max(nums[cur] + current_max, nums[cur]);
if (current_max > max) {
max = current_max;
}
cur++;
}
return max;
}
更新:
public int maxSubArray(int[] nums) {
if (nums == null) return 0;
int l = nums.length;
if (l == 1) return nums[0];
int current_max = nums[0];
int max = current_max;
for (int i = 1; i < l; i++) {
current_max = Math.max(nums[i] + current_max, nums[i]);
if (current_max > max) {
max = current_max;
}
}
return max;
}
我所做的仅有的两个改变是
- 将 while 循环更改为 for 循环 - 显然没有区别 ref
- 将长度存储在单独的变量中 - 由于 Array 不计算长度,而
array.length仅从内部变量中获取,因此我在这里也看不出有任何区别。
[编辑]
我同意。 leetcode 的性能并不是 100% 准确的。 有趣的是,我前几天再次提交了我的更新代码,现在突然变成了 0ms。
【问题讨论】:
-
Leetcode 在性能方面没有给出准确的答案。如果您想了解性能,请编写一个在您自己的硬件上运行的 JMH 基准测试。
-
看到某件事需要 0 毫秒才能完成应该已经引起了您的注意 - 任何操作都不可能立即发生。
-
0 毫秒,我假设它会在几微秒内(
标签: java performance loops