两个数组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