〖JAVA经验〗JAVA技巧(有序整数集合a和b的交集函数)

问题描述:

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

几种解决方案:

一:

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 ffset = 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() + ” “);

}

}

一起交流学习请访问:Tore_m_1206686_21115_1_1.html”>http://www.shangxueba.com/sTore_m_1206686_21115_1_1.html

最好的感觉就是你什么都跟我说。

〖JAVA经验〗JAVA技巧(有序整数集合a和b的交集函数)

相关文章:

你感兴趣的文章:

标签云: