数组交并补

来源:互联网 发布:zenm查看网络密匙 编辑:程序博客网 时间:2024/04/20 02:21
  1. http://blog.sina.com.cn/s/blog_4934a04a0100fqmf.html 

  2. //求两个字符串数组的并集,利用set的元素唯一性   
  3.     public static String[] union(String[] arr1, String[] arr2) {   
  4.         Set<String> set new HashSet<String>();   
  5.         for (String str arr1) {   
  6.             set.add(str);   
  7.         }   
  8.         for (String str arr2) {   
  9.             set.add(str);   
  10.         }   
  11.         String[] result {};   
  12.         return set.toArray(result);   
  13.     }   
  14.   
  15.     //求两个数组的交集   
  16.     public static String[] intersect(String[] arr1, String[] arr2) {   
  17.         Map<String, Boolean> map new HashMap<String, Boolean>();   
  18.         LinkedList<String> list new LinkedList<String>();   
  19.         for (String str arr1) {   
  20.             if (!map.containsKey(str)) {   
  21.                 map.put(str, Boolean.FALSE);   
  22.             }   
  23.         }   
  24.         for (String str arr2) {   
  25.             if (map.containsKey(str)) {   
  26.                 map.put(str, Boolean.TRUE);   
  27.             }   
  28.         }   
  29.   
  30.         for (Entry<String, Boolean> map.entrySet()) {   
  31.             if (e.getValue().equals(Boolean.TRUE)) {   
  32.                 list.add(e.getKey());   
  33.             }   
  34.         }   
  35.   
  36.         String[] result {};   
  37.         return list.toArray(result);   
  38.     }   
  39.   
  40.     //求两个数组的差集   
  41.     public static String[] minus(String[] arr1, String[] arr2) {   
  42.         LinkedList<String> list new LinkedList<String>();   
  43.         LinkedList<String> history new LinkedList<String>();   
  44.         String[] longerArr arr1;   
  45.         String[] shorterArr arr2;   
  46.         //找出较长的数组来减较短的数组   
  47.         if (arr1.length arr2.length) {   
  48.             longerArr arr2;   
  49.             shorterArr arr1;   
  50.         }   
  51.         for (String str longerArr) {   
  52.             if (!list.contains(str)) {   
  53.                 list.add(str);   
  54.             }   
  55.         }   
  56.         for (String str shorterArr) {   
  57.             if (list.contains(str)) {   
  58.                 history.add(str);   
  59.                 list.remove(str);   
  60.             else {   
  61.                 if (!history.contains(str)) {   
  62.                     list.add(str);   
  63.                 }   
  64.             }   
  65.         }   
  66.   
  67.         String[] result {};   
  68.         return list.toArray(result);   
  69.     }   
  70.  
0 0
原创粉丝点击