求两个数组的交集(不去重) java

public static int[] intersect(int[] num1, int[] num2){
    if (num1 == null) return num1;
    if (num2 == null) return num2;
    Arrays.sort(num1);
    Arrays.sort(num2);
    int i = 0, j = 0, k = 0;
    while (i < num1.length && j < num2.length){
        if (num1[i] < num2[j]){
            i++;
        }
        else if (num1[i] > num2[j]){
            j++;
        }
        else{
            num1[k++] = num1[i];
            i++;
            j++;
        }
    }
    return Arrays.copyOfRange(num1, 0, k);
}

 

你可能感兴趣的:(java,数据结构)