天天看点

求两个数组的交集并集并对结果排序

   这个是在自己学习了容器之后写的 

 package week13container;

/*对week13container.IntersectJiaoJi2.java的改进

* */

import java.util.*;

public class IntersectJiaoJi3 {

public static void main(String args[]) {

int[] a = { 4, 6, 7, 7, 7, 7, 8, 8, 9, 10, 100, 130, 130, 140, 150 };

int[] b = { 2, 3, 4, 4, 4, 4, 7, 8, 8, 8, 8, 9, 100, 130, 150, 160 };

intersection(a, b);

}

static void intersection(int a[], int b[]) {

Set<Integer> set1 = new HashSet<Integer>();

Set<Integer> set2 = new HashSet<Integer>();

// 去除掉数组a和b中重复的元素

for (int i = 0; i < a.length; i++) {

set1.add(a[i]);

}

for (int j = 0; j < b.length; j++) {

set2.add(b[j]);

}

// 交集

Set<Integer> su = new HashSet<Integer>(set1);

su.retainAll(set2);

System.out.println("两个数组的交集:" + sortSet(su) + "/n交集元素个数为" + su.size());

// 并集

Set<Integer> sn = new HashSet<Integer>(set1);

sn.addAll(set2);

System.out.println("两个数组的并集:" + sortSet(sn) + "/n并集元素个数为" + sn.size());

}

static String sortSet(Set<Integer> set) {//对Set进行排序的方法

Integer setArray[] = new Integer[set.size()];

Iterator<Integer> iSet = set.iterator();

for (int i = 0; iSet.hasNext(); i++) {

setArray[i] = iSet.next();// 将无序的HashSet存入到有序的数组中

}

Arrays.sort(setArray);// 排序

return Arrays.toString(setArray);//这句话执行的结果是String,所以方法的返回类型必须是String

}

}

这个是火龙果写的

package week11;

/*阿里巴巴面试题

* 问题1:马尔科夫(HMM)的特征是什么?

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

http://topic.csdn.net/u/20081012/14/3cc93688-1f7f-4985-806c-3f729c78261b.html

* */

import java.util.Arrays;

public class IntersectJiaoJi {

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;

}

}