求两个有序整数的交集并输出

2023-12-20 09:45:28
package javabase;

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr1 = {-5,3,2,3,9,13};
        int[] arr2 = {-3,1,3,4,3,3,15,13};
        int[] intersection = findIntersection(arr1, arr2);
        System.out.println(Arrays.toString(intersection));
    }
    public static int[] findIntersection(int[] arr1, int[] arr2) {
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        int[] result = new int[Math.min(arr1.length, arr2.length)];
        int i = 0, j = 0, k = 0;
        while (i < arr1.length && j < arr2.length) {
            if (arr1[i] == arr2[j]) {
                result[k++] = arr1[i];
                i++;
                j++;
            } else if (arr1[i] < arr2[j]) {
                i++;
            } else {
                j++;
            }
        }
        return Arrays.copyOf(result,k);
    }
}

文章来源:https://blog.csdn.net/u014045237/article/details/135097216
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。