Compare elements of two arrays in less than O(n^2) time?

喜你入骨 提交于 2021-02-05 06:50:12

问题


I have two integer arrays. I need to find out two numbers, one from each array, whose sum is equal to 2. This is very simple in O(n^2) but is there a way to do it faster?


回答1:


You can do it in O(N+M) time and O(N) space like this:

  • Put elements of array a into a hash set
  • Walk through array b, and check if hash table contains 2-b[i]

Constructing a hash set of N elements takes O(N) time and O(N) space. Checking each of M elements against the hash set takes O(1), for a total of O(N+M) time.



来源:https://stackoverflow.com/questions/49407831/compare-elements-of-two-arrays-in-less-than-on2-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!