1.两个有序数组中的重复数的个数
public static int commonLength(int[] a, int[] b) {
int i = 0, j = 0, count = 0;
while(i < a.length && j < b.length) {
if(a[i] > b[j]) {
j++;
} else if(a[i] < b[j]) {
i++;
} else {
count++;
i++;
j++;
}
return count;
}
}
2.两个有序数组中的重复的数
package quesion;
import java.util.ArrayList;
import java.util.List;
class FindCommon {
public static List<Integer> getCommons(int[] a , int[] b) {
List<Integer> res = new ArrayList<>();
int i = 0,j=0;
while(i < a.length && j < b.length) {
if(a[i] < b[j]) {
i++;
} else if(a[i] > b[j]) {
j++;
} else {
res.add(a[i]);
i++;
j++;
}
}
return res;
}
public static void main(String[] args) {
int a[] = {1,1,1,1,3,5,6,8,9};
int b[] = {1,1,3,5,7,10,12};
List<Integer> result = getCommons(a,b);
for (int i : result){
System.out.print(i+",");
}
}
}