两个已经有序的表的并集

来源:互联网 发布:淘宝千人千面怎么开通 编辑:程序博客网 时间:2024/06/03 21:41
package algorithm;public class Intersection {/** * a和b已经排序,求a,b的并集 * @param a * @param b */private static void intersection(int a[], int b[]) {int i = 0, j = 0, k = 0;int n = a.length;int m = b.length;int c[] = new int[100];while (i < n && j < m) {if (a[i] == b[j]) {// 相等则用c数组记录下来,i,j共同向后移动一步;c[k++] = a[i];i++;j++;while (i < n && a[i - 1] == a[i]) {// 如果等于之后,a或b数组之后出现相同的元素,则直接跳过,因为这个数已经加入到几个c中// 这里只处理a或者b跳过即可,i++;}} else if (a[i] < b[j]) {// 如果a[i]<b[j],则a[i]肯定不是a,b交集中的元素,故直接去掉(跳过),去比较a,b中剩余的元素i++;} else {j++;// //如果a[i]>b[j],则b[j]肯定不是a,b交集中的元素,故直接去掉(跳过),去比较a,b中剩余的元素}}for (int e : c) {if (e != 0)System.out.print(e + " ");}}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubint a[] = { 1, 2, 3, 3, 3, 5 };int b[] = { 2, 3, 3, 3, 5 };intersection(a, b);}}

0 0
原创粉丝点击