package com.demo;
public class TestUnion {
public static void main(String args[]){
int a[] = {1,5,8,10,14,15,17,18,20,22,24,25,28};
int b[] = {2,4,6,8,10,12};
// for(int i = 0; i < b.length; i++){
// for(int j = 0; j < a.length; j++){
// if(b[i] == a[j]){
// System.out.print(" " + b[i]);
// break;
// }
// else
// continue;
// }
// }
int i=0;
int j=0;
while(i
{
if(a[i] < b[j])
{
i++;
}
else if (a[i] == b[j])
{
System.out.println(a[i]);
i++;
j++;
}
else
{
j++;
}
}
}
}
如何求两个数组的交集,并集,差集
int[] arr1={1,2,3,4,5,6,7,8,9,10};
int[] arr2={2,4,6,8,10};
交集:
public class ArrayListTest{
public static void main(String[] args){
int[] arr1={1,2,3,4,5,6,7,8,9,10};
int[] arr2={2,4,6,8,10};
for(int i=0;i
for(int j=0;j
if(arr1[i]==arr2[j])
System.out.println(arr2[j]);
}
}
}
}
并集:
public class ArrayListTest{
public static void main(String[] args){
int[] arr1={1,2,3,4,5,6,7,8,9,10};
int[] arr2={2,4,6,8,10};
int[] arr3=new int[100];
int k=arr1.length;
int flag=0;
System.arraycopy(arr1, 0, arr3, 0, arr1.length);
for(int i=0;i
for(int j=0;j
if(arr2[i]==arr1[j]){
flag=1;
}
}
if(flag!=1){
arr3[k]=arr2[i];
k++;
}
flag=0;
}
for(int z=0;z
System.out.print(arr3[z]);
}
}
}
差集:
public class ArrayListTest{
public static void main(String[] args){
int[] arr1={1,2,3,4,5,6,7,8,9,10};
int[] arr2={2,4,6,8,10};
int[] arr3=new int[100];
int k=0;
int flag=0;
for(int i=0;i
for(int j=0;j
if(arr2[j]==arr1[i]){
flag=1;
}
}
if(flag!=1){
arr3[k]=arr1[i];
k++;
}
flag=0;
}
for(int z=0;z
System.out.print(arr3[z]);
}
}
}
分享到:
2010-03-16 17:36
浏览 2542
评论
2 楼
nextw3
2011-05-24
残念,代码写错了
1 楼
nextw3
2011-05-24
//并集
public class ArrayListTest{
public static void main(String[] args){
int[] arr1={1,2,3,4,5,6,7,8,9,10};
int[] arr2={2,4,6,8,10};
int[] arr3=new int[100];
int k=arr1.length;
System.arraycopy(arr1, 0, arr3, 0, arr1.length);
for(int i=0;i
for(int j=0;j
if(arr2[i]==arr1[j]){
break;
}
arr3[k]=arr2[i];
k++;
}
}
for(int z=0;z
System.out.print(arr3[z]);
}
}
}
去掉flag变量,用break控制。这样不是更好吗?