简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM