两个已排序数组,找出相同的部分
2011-12-12 23:14
573 查看
存在的两个数组,已经排好顺序,求其相同的部分,有以下几种求法:
1) 穷举法
最原始的方法,时间复杂度为O(m*n),代码如下:
2) binary search
通过一个数组的for循环,不断与另一数组的中间值比较,时间复杂度为O(nlogn),代码如下:
3) hashMap
把其中的一个数组装进hashmap,拿另外一个数组来取值,为空则不相同,时间复杂度为O(n),代码如下:
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); } }
相关文章推荐
- 找出两个数组中相同的元素,不排序直接两次循环取出
- javascript 常见数组操作( 1、数组整体元素修改 2、 数组筛选 3、jquery 元素转数组 4、获取两个数组中相同部分或者不同部分 5、数组去重并倒序排序 6、数组排序 7、数组截取slice 8、数组插入、删除splice(需明确位置) 9、数组遍历 10、jQuery根据元素值删除数组元素的方)
- 【算法题】找出两个已序数组,是否含有相同的数字
- 实训汇编语言设计——找出两个数组中相同的整数
- 字符串数组 string[] 转换为 字符串(用逗号,作为分隔符),linq Except的用法,linq获取两个字符串数组相同的部分
- 找出两个有序数组中相同的元素
- php找出两个有序数组中的相同元素
- 比较高效地实现从两个不同数组中提取相同部分组成新的数组(暂时只支持Int类型)
- 两个排序后数组中是否存在相同数字
- 找出两个已排序且同序大小相等的数组的中位数C语言
- php两个数组合并在一起,根据两个数组相同的键进行排序(时间排序)
- 找出两个字符串数组中的相同元素
- 两个大数组foreach,找出相同的key数量,所用的时间对比
- 笔试算法题(28):删除乱序链表中的重复项 & 找出已经排好序的两个数组中的相同项
- 两个有序整形数组找出二者相同的元素和不同的元素
- 找出删除两个文件相同部分Linux_grep,comm,awk
- 两个大数组foreach,找出相同的key数量,所用的时间对比
- 两个有序数组长度分别为m,n,最多m+n次查找找出相同的数
- 找出排序数组中和为给定值的两个数字
- JAVA两个数组间元素的比较(找出相同或者不同元素)