Arrays 更高效地打印两个数组的交集(Java)
这是关于数据结构的,我的教授希望我写得有效率,所以如果他找到一个更有效的,我就完成了,哈哈。。。有没有一种不使用两个循环就能得到它的方法?(不要使用hashtags) 1个循环将是最有效的Arrays 更高效地打印两个数组的交集(Java),arrays,intersection,Arrays,Intersection,这是关于数据结构的,我的教授希望我写得有效率,所以如果他找到一个更有效的,我就完成了,哈哈。。。有没有一种不使用两个循环就能得到它的方法?(不要使用hashtags) 1个循环将是最有效的 谢谢大家既然它被证明是有用的,我将把它作为一个答案发布。也许有人也会用它 答案如下: 链接中的示例: // Java program to find intersection of // two sorted arrays class FindIntersection { /* Function p
谢谢大家既然它被证明是有用的,我将把它作为一个答案发布。也许有人也会用它 答案如下: 链接中的示例:
// Java program to find intersection of
// two sorted arrays
class FindIntersection
{
/* Function prints Intersection of arr1[] and arr2[]
m is the number of elements in arr1[]
n is the number of elements in arr2[] */
static void printIntersection(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while (i < m && j < n)
{
if (arr1[i] < arr2[j])
i++;
else if (arr2[j] < arr1[i])
j++;
else
{
System.out.print(arr2[j++]+" ");
i++;
}
}
}
public static void main(String args[])
{
int arr1[] = {1, 2, 4, 5, 6};
int arr2[] = {2, 3, 5, 7};
int m = arr1.length;
int n = arr2.length;
printIntersection(arr1, arr2, m, n);
}
}
//查找交叉点的Java程序
//两个排序数组
类FindIntersection
{
/*函数打印arr1[]和arr2[]的交点
m是arr1[]中的元素数
n是arr2[]中的元素数*/
静态无效打印交点(int arr1[],int arr2[],int m,int n)
{
int i=0,j=0;
而(i
既然它被证明是有用的,我将把它作为一个答案发布。也许有人也会用它
答案如下:
链接中的示例:
// Java program to find intersection of
// two sorted arrays
class FindIntersection
{
/* Function prints Intersection of arr1[] and arr2[]
m is the number of elements in arr1[]
n is the number of elements in arr2[] */
static void printIntersection(int arr1[], int arr2[], int m, int n)
{
int i = 0, j = 0;
while (i < m && j < n)
{
if (arr1[i] < arr2[j])
i++;
else if (arr2[j] < arr1[i])
j++;
else
{
System.out.print(arr2[j++]+" ");
i++;
}
}
}
public static void main(String args[])
{
int arr1[] = {1, 2, 4, 5, 6};
int arr2[] = {2, 3, 5, 7};
int m = arr1.length;
int n = arr2.length;
printIntersection(arr1, arr2, m, n);
}
}
//查找交叉点的Java程序
//两个排序数组
类FindIntersection
{
/*函数打印arr1[]和arr2[]的交点
m是arr1[]中的元素数
n是arr2[]中的元素数*/
静态无效打印交点(int arr1[],int arr2[],int m,int n)
{
int i=0,j=0;
而(i
“一个循环”且只有在数组已排序或可能的数字范围有限的情况下,才可能没有哈希集。您尝试过这个吗?时间复杂度:O(m+n)嗨@Slai,抱歉我忘了说,它们被分类了:)@SebastianKaczmarek哇!这是金子!谢谢没问题;)我把它作为一个答案发布,这样更多的人可以看到它“一个循环”,并且只有当数组被排序或者可能的数字范围有限时,才可能没有哈希集。您尝试过这个吗?时间复杂度:O(m+n)嗨@Slai,抱歉我忘了说,它们被分类了:)@SebastianKaczmarek哇!这是金子!谢谢没问题;)我把它作为一个答案贴了出来,这样更多的人可以看到它