开发者

How can I find objects that are in BOTH arrays and promptly add it to another array?

How can I create a method that recieve two arrays as parameters and return an array filled with the items that were in both arrays?

Input (Array1 passed in method): ["Lisa", "George", "Mario"] Input (Array2 passed in method): ["Luigi", "Susan", "Lisa"]

Method should return: ["Lisa"]

I cannot use any built in methods so I have to build my own algorithm, but I'm stuck for the开发者_如何学JAVA past 2 hours. How can I achieve this in Java?

Edit: Christ on a candle stick. It's not for homework. I'm just real shitty at algorithms. Especially ones as basic as this, and especially on a foreign language I've never used. :P


How about:

private static String[] findCommon(final String[] array1,
        final String[] array2) {
    final Set<String> common = new HashSet<String>();
    common.addAll(Arrays.asList(array1));
    common.retainAll(Arrays.asList(array2));
    return common.toArray(new String[0]);
}


One quick way is the following algorithm:

For each item in list1, add it to a dictionary.
For each item in list2, check if it exists in dictionary, 
if item exists, add it to list3
else continue.
return list3.


Brute force.

Loop over the first array. Inside that loop, have another over the second array. Compare entries from both, adding them to a new array if you get a match.


    [] result = ...

    foreach( itemA in a ) {
        foreach(  iteamB in b ) {
             if( itemB == itemA ) { // if they are in both places
                   r[] = itemB // append it to the result
             }
         }
    }
    return result;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜