您的位置:首页 > 其它

两个已排序数组,找出相同的部分

2011-12-12 23:14 573 查看
存在的两个数组,已经排好顺序,求其相同的部分,有以下几种求法:

1) 穷举法

最原始的方法,时间复杂度为O(m*n),代码如下:

int a[] = new int[]{3,9,20,34,12,38}; //示列数组
int b[] = new int[]{6,3,20,19,23,32,34,37};
for (int i = 0 ; i < a.length; i++) {
for (int j = 0 ; j < b.length; j++) {
if (a[i] == b[j]) {
System.out.println(i); //输出a的下标;
}

}
}


2) binary search

通过一个数组的for循环,不断与另一数组的中间值比较,时间复杂度为O(nlogn),代码如下:

int a[] = new int[]{3,9,12,20,34,38};
int b[] = new int[]{3,6,19,20,23,32,34,37};
for (int i = 0 ; i < a.length; i++) {
int start = 0,end = b.length - 1, mid ;
while(start <= end) {
mid = (end + start)/2;  //取中间值
if (a[i] == b[mid] ) {
System.out.println(i);
break;
} else if(a[i] < b[mid]) {
end = mid-1;
} else {
start = mid + 1;
}
}
}


3) hashMap

把其中的一个数组装进hashmap,拿另外一个数组来取值,为空则不相同,时间复杂度为O(n),代码如下:

int a[] = new int[]{3,9,12,20,34,38};
int b[] = new int[]{3,6,19,20,23,32,34,37};
Map hashMap = new HashMap();
for (int i = 0 ; i < a.length ; i++) {
hashMap.put(a[i], "true");  //把a数组装进hashmap
}

for (int j = 0 ; j < b.length; j++) {
String str = (String)hashMap.get(b[j]);  //用b中的值和hashmap比较,为空则不相同
if (str != null) {
System.out.println(j);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐