给定两个已排序数组,找出相同数

该博客介绍了如何通过双指针法解决寻找两个已排序数组中相同元素的问题。当指针指向的元素相等时,将它们添加到结果列表中;如果不等,则移动指向较小元素的指针。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路

  1. 两个指针分别指向序列的开始
  2. 若指向的两个元素相等,则加入commoList
  3. 如果不等,则指向较小元素的指针向后移动
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;
	   }
	}
			```
			
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值