Finding duplicate values between two arrays

前端 未结 6 1160
死守一世寂寞
死守一世寂寞 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条回答
  •  Happy的楠姐
    2020-12-09 23:25

    These solutions all take O(n^2) time. You should leverage a hashmap/hashset for a substantially faster O(n) solution:

    void findDupes(int[] a, int[] b) {
        HashSet map = new HashSet();
        for (int i : a)
            map.add(i);
        for (int i : b) {
            if (map.contains(i))
                // found duplicate!   
        }
    }
    

提交回复
热议问题