Finding duplicate values between two arrays

前端 未结 6 1169
死守一世寂寞
死守一世寂寞 2020-12-09 22:56

Let\'s say I have the following two arrays:

int[] a = [1,2,3,4,5];
int[] b = [8,1,3,9,4];

I would like to take the first value of array

6条回答
  •  再見小時候
    2020-12-09 23:09

    Depending on the data (its size, whether every value is unique, etc) and what you're trying to get from it (ie, whether each element of a is in b, or also its index in b), it may be beneficial to do a bit of overhead work before you do the meat of it. For instance, if you sort both arrays (which you'll only need to do once), you can start the inner loop where you stopped it last (since you know that you're looking for a number >= the one you looked for last, so it's got to be at this index or greater), and you can also stop the inner loop sooner (since you know that if you're looking for X and you haven't found it before seeing a value > X, then X isn't there). Another approach would be to load both values into a Set, which you can now probe efficiently.

提交回复
热议问题