思路
- 两个指针分别指向序列的开始
- 若指向的两个元素相等,则加入commoList
- 如果不等,则指向较小元素的指针向后移动
public class five2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ProductionList();
}
public static void ProductionList() {
int m,n;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入数组a的大小:");
m = scanner.nextInt();
int a[] = new int[m];
System.out.println("请输入数组a的元素:");
for (int i = 0; i < m; i++) {
a[i] = scanner.nextInt();
}
System.out.println("请输入数组b的大小:");
n = scanner.nextInt();
int b[] = new int[n];
System.out.println("请输入数组b的元素:");
for (int i = 0; i < n; i++) {
b[i] = scanner.nextInt();
}
List<Integer> c = FindCommon(a, b);
for (Integer integer : c) {
System.out.print("相同数如下"+integer+" ");
}
}
public static List<Integer> FindCommon(int a[],int b[]) {
List<Integer> commList = new ArrayList<Integer>();//用于存放相同的数
if (!(a!=null&&a.length>0&&b!=null&&b.length>0))
return commList;
int lengthA = a.length;
int lengthB = b.length;
for (int i = 0,j = 0; i < lengthA && j < lengthB; )
{
if (a[i] < b[j]) {
i++;
}
else if (a[i] > b[j]) {
j++;
}
else {
commList.add(a[i]);
i++;
j++;
}
}
return commList;
}
}
```