有两个有序整数聚合a和b,写一个函数找出它们的交集

有两个有序整数集合a和b,写一个函数找出它们的交集?
这个题目,是无意在在****网站上 一位论坛网友发布的题目,感兴趣,就自己写了一种算法

问题2:有两个有序整数集合a和b,写一个函数找出它们的交集?

我的解法:

package com.filename;

import java.util.*;

public class Test {

   public static void main(String[] args) {
        int[] a = new int[] { 1, 2, 4, 5, 9 };
        int[] b = new int[] { 3, 6, 9, 10, 12 };

        Set set = null;
        set = Test.getResult(a, b);
        if (set != null) {
          for (Iterator it = set.iterator(); it.hasNext();) {
            System.out.print(it.next());
          }
        } else {
          System.out.println("没有交集");
        }
      }

     public static Set getResult(int[] m, int[] n) {
        Set set = new HashSet();
        Set newSet = new HashSet();
        for (int i = 0; i < m.length + n.length; i++) {
          if (i < m.length) {
            set.add(m[i]);
          } else {
            if (set.contains(n[i - m.length])) {
              newSet.add(n[i - m.length]);
            } else {
              set.add(n[i - m.length]);
            }
          }
        }
        return newSet;
      }
}


请大家看一下


本文来自****博客,转载请标明出处:http://blog.****.net/love_zhangxsh_love/archive/2008/10/18/3094755.aspx
1 楼 tianweibytj 2011-12-05  
[b][/b][i][/i][u][/u]
引用

[img][/img][url][/url][flash=200,200][/flash]