求两个集合的交集

来源:互联网 发布:国内实时数据库 编辑:程序博客网 时间:2024/05/18 03:30

转自:http://www.k6k4.com/blog/show/aaajyefii1506524723567

如:集合A={1,2,3,4}, B={5,3,4}, 结果为:result={3,4}


方法一:排序法

  • 思路:先对两个集合进行排序O(nlogn),然后通过一遍查询比较O(n), 即可找出两个集合的交集


  1. public static void main(String[] args) {
  2.  
  3. List<Integer> listA = new ArrayList<Integer>();
  4. listA.add(1);
  5. listA.add(2);
  6. listA.add(3);
  7. listA.add(4);
  8. List<Integer> listB = new ArrayList<Integer>();
  9. listB.add(5);
  10. listB.add(3);
  11. listB.add(4);
  12. //排序O(nlogn)
  13. Collections.sort(listA);
  14. Collections.sort(listB);
  15.  
  16. //一次遍历O(n)
  17. for (int i = 0, j = 0; i < listA.size() && j < listB.size(); ) {
  18. if (listA.get(i) < listB.get(j)) {
  19. i++;
  20. } else if (listA.get(i) > listB.get(j)) {
  21. j++;
  22. } else {
  23. System.out.print(listA.get(i) + " ");
  24. i++;
  25. j++;
  26. }
  27.  
  28. }
  29.  
  30. }


方法二:Hash法

  • 思路:将较小的集合放入hash表里O(n),然后逐个遍历大表中的每个元素是否在hash表里O(n),需要消耗O(n)的空间

  1. public static void main(String[] args) {
  2.  
  3. List<Integer> listA = new ArrayList<Integer>();
  4. listA.add(1);
  5. listA.add(2);
  6. listA.add(3);
  7. listA.add(4);
  8. List<Integer> listB = new ArrayList<Integer>();
  9. listB.add(5);
  10. listB.add(3);
  11. listB.add(4);
  12.  
  13. //将集合B加入Hash表里,耗时O(n), 空间消耗O(size(listB))
  14. Set<Integer> setB = new HashSet<Integer>();
  15. for (int i = 0; i < listB.size(); i++) {
  16. setB.add(listB.get(i));
  17. }
  18.  
  19. //一次遍历O(n)
  20. for (int i = 0; i < listA.size(); i++) {
  21. if (setB.contains(listA.get(i))) {
  22. System.out.print(listA.get(i) + " ");
  23. }
  24. }
  25.  
  26. }

方法三:集合压缩法

     http://blog.csdn.net/jie1991liu/article/details/13168255

方法四:位图法

   http://blog.csdn.net/moli152_/article/details/48163351


转自:http://www.k6k4.com/blog/show/aaajyefii1506524723567

原创粉丝点击