更新时间:2023-02-10 23:11:32
效率明显提高:先对整数进行排序,然后再查看相邻的整数。任何数字都会向上或向下最接近其邻居。
One obvious efficiency improvement: sort the integers first, then you can look at adjacent ones. Any number is going to be closest to its neighbour either up or down.
这会改变O的复杂度(n 2 )到O(n log n)。对于 n
的较小值,它不会产生明显的变化,但是就理论上的复杂性而言,这很重要。
That changes the complexity from O(n2) to O(n log n). Admittedly for the small value of n
shown it's not going to make a significant difference, but in terms of theoretical complexity it's important.
您可能需要进行一次微优化:使用局部变量存储 Math的结果。 abs
,那么如果结果小于最小值,则无需重新计算。您可能想使用 dMin = Math.min(dMin,Math.abs(a [i]-a [j]))
。
One micro-optimization you may want to make: use a local variable to store the result of Math.abs
, then you won't need to recompute it if that turns out to be less than the minimum. Alternatively, you might want to use dMin = Math.min(dMin, Math.abs(a[i] - a[j]))
.
请注意,您需要注意边界条件-如果您允许使用负数,则减法可能会溢出。
Note that you need to be careful of border conditions - if you're permitting negative numbers, your subtraction might overflow.