这就是问题所在:
Given 3 random arrays of integers, write a method to find the smallest number that is common among the 3 arrays. HINT: Sort first and just traverse first few elements until you reach the common number
[-1,-2, 4,5,6,1,2,3,3,3,1,1,1]
[54,6,7,8,1,3,5,1]
[1,6,9,1,0,2,1]
result = 1我编写了一个可行的解决方案代码,但我想知道是否有一种更简单、更有效的方法来做到这一点。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Smcomm {
public static void main(String[] args) {
int[] A = {-1,-2,4,5,6,1,2,3,3,3,1,1,1};
int[] B = {54,6,7,8,1,3,5,1};
int[] C = {1,6,9,1,0,2,1};
ArrayList<Integer> ar1 = new ArrayList<Integer>();
ArrayList<Integer> ar2 = new ArrayList<Integer>();
ArrayList<Integer> ar3 = new ArrayList<Integer>();
for(int el: A){
ar1.add(el);
}
for(int el: B){
ar2.add(el);
}
for(int el: C){
ar3.add(el);
}
Collections.sort(ar1);
Collections.sort(ar2);
Collections.sort(ar3);
printer(ar1);
printer(ar2);
printer(ar3);
finder(ar1,ar2,ar3);
}
static void printer(ArrayList ar){
Iterator<Integer> it = ar.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println("--------------------");
}
static void finder(ArrayList ar1, ArrayList ar2, ArrayList ar3){
ar1.retainAll(ar2);
ar1.retainAll(ar3);
if(ar1.size()>0){
System.out.println(ar1.get(1));
}else {
System.out.println("no comm el");
}
}
}不完全适合我的方法是retainAll,因为我认为它的复杂度为O(n^2)。
我不需要找到所有的元素,但我只想找到最小的元素。当方法在数组中找到共同的第一个元素时,您知道是否有可能停止该方法的执行吗?应该不难,因为数组已经排序了。
谢谢你的帮助。
发布于 2019-06-12 12:53:54
一种略有不同的办法:
其他两个项中包含的第一个数字必须是最小的公共项。这使您无法查看重复的条目(这在这里并不重要),而且它也避免了对所有三个数组进行排序。
最后,对于这样的小例子,任何正确的解决方案都是足够好的。对于不同的解决方案,潜在的权衡只有在你谈论有成千上万甚至数百万条目的列表时才会起作用。
发布于 2019-06-12 12:48:42
发布于 2019-06-12 13:17:13
您只能使用数组和foreach循环来以简单的方式实现这一点:
这里是如何实现这一目标的一个例子:
public static void main(String[] args) {
int[] A = {-1, -2, 4, 5, 6, 1, 2, 3, 3, 3, 1, 1, 1};
int[] B = {54, 6, 7, 8, 1, 3, 5, 1};
int[] C = {1, 6, 9, 1, 0, 2, 1};
Arrays.sort(A);
Arrays.sort(B);
Arrays.sort(C);
Optional<Integer> inCommon = findInCommon(A, B, C);
if (inCommon.isPresent()) {
System.out.println(inCommon.get());
} else {
System.out.println("no comm el");
}
}
private static Optional<Integer> findInCommon(int[] A, int[] B, int[] C) {
int lastB = 0;
int lastC = 0;
for (int valA : A) {
while (B[lastB] < valA) lastB++;
while (C[lastC] < valA) lastC++;
if (valA == B[lastB] && valA == C[lastC]) {
return Optional.of(valA);
}
}
return Optional.empty();
}https://stackoverflow.com/questions/56562513
复制相似问题