Find two identical elements in the array --- Java

Two traversal

After thinking it out two ways, the first in two arrays, each array element can not duplicate , you can direct the cycle of violence, complexity is O (n2) , and this method is only applicable to arr1 and It does not exist in each of the repeating element arr2.

public static List<Integer> findSame(int[] arr1, int[] arr2) {
        List<Integer> list = new ArrayList<>();
        if (arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0) {
            return list;
        }
        for(int i=0;i<arr1.length;i++) {
            for(int j=0;j<arr2.length;j++)
                if(arr1[i]==arr2[j]) {
                    list.add(arr1[i]);
                }
        }
        return list;
    }

Merge ideas

Merging thought, complexity is O (N + M) , M and N are the length of the two arrays, this method is much higher than the efficiency of the method of violence, but only if ordered, if the order is not, then the first to sort, sort ordering complexity O (nlogn) , or above certainly add complexity O (n2), but this method is applicable to the presence of repetitive elements of two arrays.

This method sets an array of two pointers, shift after the time when equal, if not equal, small who who ++, catch-me, a complete traversal of any array, it can be ended.

    public static List<Integer> findCommon(int[] arr1, int[] arr2) {
        List<Integer> list = new ArrayList<>();
        if (arr1 == null || arr2 == null || arr1.length == 0 || arr2.length == 0) {
            return list;
        }
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        int i = 0, j = 0;
        while ( i < arr1.length && j < arr2.length ) {
            if (arr1[i] == arr2[j]) {
                list.add(arr1[i]);
                i++;
                j++;
            } 
            else if (arr1[i] < arr2[j]) i++;
            else j++;
        }
        return list;
    }

 

Guess you like

Origin blog.csdn.net/Hollake/article/details/92803664