日期:2014-05-20  浏览次数:20724 次

获得n个String数组相同元素算法?
假设有5个字符串数组,每个有100个元素,要获得这5个数组中都包含的元素的个数怎么写呢?
例:
String[]   a   ={ "1 ", "33 ", "55 ", "67 "};
String[]   b   ={ "1 ", "56 ", "97 ", "111 ", "33 "};
String[]   c   ={ "1 ", "11 ", "22 ", "33 "};
String[]   d   ={ "1 ", "33 "};
String[]   e   ={ "1 ", "2 ", "3 ", "33 "};
这五个数组的相同元素为2个。




------解决方案--------------------
先想到个最慢的方法,for嵌套,选中一个,然后遍历其他的。

应该还有更好的方法,thinking......
------解决方案--------------------
求出长度最小的数姐,以长度最小数组元素为基数,
初始化一个整型变量比如n,
比较其余数组,相同刚输出,n++;
大概就这样,参考下
------解决方案--------------------
import java.util.ArrayList;
import java.util.List;


public class Test2 {
public static void main(String[]str) {
String[] a ={ "1 ", "33 ", "55 ", "67 "};
String[] b ={ "1 ", "56 ", "97 ", "111 ", "33 "};
String[] c ={ "1 ", "11 ", "22 ", "33 "};
String[] d ={ "1 ", "33 "};
String[] e ={ "1 ", "2 ", "3 ", "33 "};

ArrayList list = new ArrayList();
list.add(a);
list.add(b);
list.add(c);
list.add(d);
list.add(e);

System.out.println(new Test2().find(list).size());
}

public List find(List list) {
String[]strArray1 = (String[]) list.get(0);
List arrList = new ArrayList();
for (int i = 0; i < strArray1.length; i++) {
arrList.add(strArray1[i]);
}

for (int i = 1; i < list.size() - 1; i++) {
String[]strArray2 = (String[]) list.get(i);
arrList = compare(arrList, strArray2);
}
return arrList;
}

public List compare(List a, String[] b) {
List resultList = new ArrayList();
for (int i = 0; i < b.length; i++) {
for (int j = 0; j < a.size(); j++) {
if (a.get(j).equals(b[i])) {
resultList.add(a.get(j));
break;
}
}
}
return resultList;
}
}

------解决方案--------------------
可不可以先放到集合里面。然后再研究一下这个方法retainAll(Collection <?> c)
------解决方案--------------------
public class Test
{
static String[] strcomp(String[] s1, String[] s2)
{
if(s1.length <= s2.length)
return s1;
else
return s2;
}

static String[] strcompR(String[] s1, String[] s2, String[] s3, String[] s4, String[] s5)
{
return strcomp(strcomp(strcomp(strcomp(s1, s2), s3), s4), s5);
}

static boolean comp(String s, String[] a)
{
boolean k = true;
for(String i : a)
{
if(i == s)
{
k = true;
break;
}
else
k = false;
}
return k;
}

public static void main(String[] args)
{
String[] a ={ "1 ", "33 ", "55 ", "67 "};