两个数组a和b,都已经升序排列. 查找相同的元素?(要求不使用两层for循环)

int[] a = { 1, 3, 5, 7, 9, 24, 88, 108, 126, 139 };
int[] b = { 2, 5, 24, 88, 108, 110, 112, 126 };

查找a和b相同的元素,目标结果:

5
24
88
108
126

 这个题目,首先要利用这两个数组已经是升序排列的特性,解题思路是使用2个游标分别指向两个数组正在比较的元素的下标。

分3种情况

1)a[aIndex] < b[bIndex] :

    aIndex右移

2)a[aIndex] > b[bIndex]:

    bIndex右移

3)a[aIndex] == b[bIndex]:

     获取到一个相同的元素,aIndex、bIndex同时右移

上代码:

 1 import java.util.ArrayList;
 2 import java.util.List;
 3 
 4 public class FindTheSame {
 5 
 6   public static void main(String[] args) {
 7     int[] a = { 1, 3, 5, 7, 9, 24, 88, 108, 126, 139 };
 8     int[] b = { 2, 5, 24, 88, 108, 110, 112, 126 };
 9     List<Integer> c = findTheSame(a, b);
10     for(int i : c){
11       System.out.println(i);
12     }
13   }
14 
15   private static List<Integer> findTheSame(int[] a, int[] b) {
16     List<Integer> c = new ArrayList<Integer>();
17     int aIndex = 0, bIndex = 0;
18     while(aIndex < a.length && bIndex < b.length){
19       if(a[aIndex] < b[bIndex]) aIndex++;
20       else if(a[aIndex] > b[bIndex]) bIndex++;
21       else {
22         c.add(a[aIndex]);
23         aIndex++;
24         bIndex++;
25       }
26     }
27     return c;
28   }
29 
30 }

运行效果:

5
24
88
108
126

 

转载于:https://www.cnblogs.com/sunny08/p/8657988.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值