JAVA技巧(有序整數(shù)集合a和b的交集函數(shù))

字號:

問題描述:
    有兩個有序整數(shù)集合a和b,寫一個函數(shù)找出它們的交集?
    幾種解決方案:
    一:
    import java.util.Arrays;
    public class Test {
    public static void main(String args[]){
    int[] b = {4, 6, 7, 7, 7, 7, 8, 8, 9, 10, 100, 130, 130, 140, 150};
    int[] a = {2, 3, 4, 4, 4, 4, 7, 8, 8, 8, 8, 9, 100, 130, 150, 160};
    int[] c = intersect(a, b);
    System.out.println(Arrays.toString(c));
    }
    public static int[] intersect(int[] a, int[] b) {
    if(a[0] > b[b.length - 1] || b[0] > a[a.length - 1]) {
    return new int[0];
    }
    int[] intersection = new int[Math.max(a.length, b.length)];
    int offset = 0;
    for(int i = 0, s = i; i < a.length && s < b.length; i++) {
    while(a[i] > b[s]) {
    s++;
    }
    if(a[i] == b[s]) {
    intersection[offset++] = b[s++];
    }
    while(i < (a.length - 1) && a[i] == a[i + 1]) {
    i++;
    }
    }
    if(intersection.length == offset) {
    return intersection;
    }
    int[] duplicate = new int[offset];
    System.arraycopy(intersection, 0, duplicate, 0, offset);
    return duplicate;
    }
    }
    二:
    import java.util.ArrayList;
    public class jiaoji {
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    int[] b = { 4, 6, 7, 7, 7, 8, 8, 9, 10, 100, 130, 140, 150 };
    int[] a = { 2, 3, 4, 4, 4, 7, 8, 8, 8, 8, 9, 100, 130, 150, 160 };
    ArrayList c = sect(a, b);
    for (int i = 0; i < c.size(); i++) {
    System.out.print(c.get(i) + ",");
    }
    }
    public static ArrayList sect(int[] a, int[] b) {
    int k = 0;
    int startposb = 0;
    if (a[0] > b[b.length - 1] || b[0] > a[a.length - 1]) {
    return new ArrayList();
    }
    ArrayList arraylist = new ArrayList();
    for (int i = 0; i < a.length; i++) {
    for (int j = startposb; j < b.length; j++) {
    if (a[i] == b[j]) {
    arraylist.add(k, a[i]);
    k++;
    startposb = j + 1;
    break;
    }
    }
    }
    return arraylist;
    }
    }
    三:
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    public class NumberCross {
    public static void main(String[] args) {
    int a[] = {1,3,4,5,6,7,499,199};
    int b[] = {3,299,199,8,9,499};
    Set list = new HashSet();
    for(int i=0; i  list.add(a[i]);
    }
    for(int j=0; j    list.add(b[j]);
    }
    for(Iterator iter=list.iterator(); iter.hasNext();) {
    System.out.print(iter.next() + " ");
    }
    }
    }