且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

找到两个数组中2个数字之间的距离

更新时间:2022-10-31 23:10:10

CPallini是对的,所以排序可以提高你的循环速度,因为你可以在diff时停止循环大于num。如果数字小于num,请考虑删除一些比较。也许只有当大于零时。



如果你需要找到这些数字,你也必须存储它们以便输出。



CPallini is right, so ordering could improve the speed of your loop because your can stop the looping when the diff gets greater than num. Think about dropping some comparison if the numbers are smaller than num. Maybe only if alway greater than zero.

If you need to find the numbers you also must store them for output.

if (abs(a[i] - b[j]) == num)
  {
    result1 = a[i];//store in variable with greater scope
    result2 = b[i];
    return 1;
}

阵列中的多个解决方案怎么样?



但速度不是这个简单任务的主要问题。这种优化通常会导致复杂而奇怪的代码,从而导致奇怪的错误和问题。



所以你错过了什么?

What about multiple solutions in the array?

But speed isnt the primary problem on that simple task. Such "optimization" often leads to complex and bizarre code which results in strange bugs and problems.

So anything you missed to mention?