Example 1
a1 = ["arp", "live", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns ["arp", "live", "strong"]
Example 2
a1 = ["tarp", "mice", "bull"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns []
javascript版本
1.自己
function inArray(array1,array2){
//...
return array1.reduce((acc,cur,index)=>{
if(array2.join("-").indexOf(cur) > -1){
acc.push(cur);
}
return acc;
},[]).sort();
}
2.他人
function inArray(arr1, arr2) {
return arr1.filter(function(needle) {
return arr2.some(function(haystack) {
return haystack.indexOf(needle) > -1;
});
}).sort();
}
3.他人
function inArray(array1,array2){
return array1
.filter(a1 => array2.find(a2 => a2.match(a1)))
.sort()
}
function inArray(a1, a2) {
var r = [];
for (var i = 0; i < a1.length; i++) {
var s1 = a1[i];
for (var j = 0; j < a2.length; j++) {
var s2 = a2[j];
if (s2.indexOf(s1) != -1 && r.indexOf(s1) == -1) {
r.push(s1);
}
}
}
return r.sort();
}
java版本
1.自己
import java.util.*;
public class WhichAreIn {
public static String[] inArray(String[] array1, String[] array2) {
List<String> fin = new ArrayList();
for(int i = 0 ; i < array1.length ; i++){
String a1 = array1[i];
for(int j = 0 ; j < array2.length; j++){
String a2 = array2[j];
if(a2.indexOf(a1) > -1 && fin.indexOf(a1) < 0){
fin.add(a1);
}
}
}
Collections.sort(fin);
return fin.toArray(new String[fin.size()]);
}
}
2.他人
import java.util.Arrays;
public class WhichAreIn {
public static String[] inArray(String[] array1, String[] array2) {
return Arrays.stream(array1)
.filter(str ->
Arrays.stream(array2).anyMatch(s -> s.contains(str)))
.distinct()
.sorted()
.toArray(String[]::new);
}
}
暂时还无法理解 String[]::new,还需要学习lambda表达式
3.他人
import java.util.Set;
import java.util.HashSet;
import java.util.Arrays;
public class WhichAreIn {
public static String[] inArray(String[] array1, String[] array2) {
Set<String> result = new HashSet<>();
for(String a1 : array1) {
for(String a2 : array2) {
if(a2.contains(a1)) {
result.add(a1);
break;
}
}
}
String[] resultArray = result.toArray(new String[result.size()]);
Arrays.sort(resultArray);
return resultArray;
}
}