两个有序且有重复的数组,合并为一个无重复的有序数组
比如a={1,1,1,2,2,4,8,9,17,18,19,25,30,35};b={3,6,6,9,10,15,16,19,25};
合并结果为c={1, 2, 3, 4, 6, 8, 9, 10, 15, 16, 17, 18, 19, 25, 30, 35};
算法代码为:
List<Integer> mergeList(int[] a, int[] b){
List<Integer> result=new ArrayList<Integer>();
int i = 0,j = 0;
while(i<a.length&&j<b.length){
if(i!=a.length-1 && a[i]==a[i+1]){
i++;
continue;
}
if(j!=b.length-1 && b[j]==b[j+1]){
j++;
continue;
}
if(a[i]>b[j]){
result.add(b[j++]);
}else if(a[i]<b[j]){
result.add(a[i++]);
}else if(a[i]==b[j]){
result.add(a[i]);
i++;
j++;
}
}
while(i<a.length){
result.add(a[i++]);
}
while(j<b.length){
result.add(b[j++]);
}
return result;
}
测试代码为:
<pre name="code" class="html">
void testMergeList(){
int a[]={1,1,1,2,2,4,8,9,17,18,19,25,30,35};
int b[]={3,6,6,9,10,15,16,19,25};
List<Integer> c = mergeList(a,b);
System.out.println("xuejiao c = "+c);
//Log.d("xuejiao","xuejiao c = "+c);
}