代码多次返回0和常用数。我希望它只返回一次包含公共数字的数组!那么,我如何返回一个包含两个数组通用数字的数组呢?我想返回{2,7,4} -就像这样。当我试图返回一个数组时,我总是得到越界的异常。谢谢,巴里
public class Test {
public int findCommonElement(int[] a, int[] b){
int counter=0;
int temp= 0;
int tempCounter = 0;
for(int i=0; i<a.length; i++){
temp=a[i];
tempCounter=0;
for(int j=0; j<b.length; j++){
if (temp==b[j]){
tempCounter++;
}
}
if (tempCounter == 1) {
temp = a[i];
counter++;
System.out.println(temp);
}
}
return 0;
}
public static void main(String []args){
int myArray[] = {2,2,7,7,2,1,5,4,5,1,1};
int myArray2[] = {2,3,4,7,10};
Test hello = new Test ();
System.out.println(hello.findCommonElement(myArray, myArray2));
}
}
发布于 2016-11-16 22:00:39
基本上,来自两个元素的公共元素的数量将是动态的。因此,如果您试图将公共元素放入一个数组中,那么这是不可能的,因为您需要声明这个数组的大小(在本例中,它将是动态的)。
考虑使用list。我尽量使逻辑尽可能简单,同时提供全面的变量名。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test {
public static void main(String[] args) {
int myArray[] = { 2, 2, 7, 7, 2, 1, 5, 4, 5, 1, 1 };
int myArray2[] = { 2, 3, 4, 7, 10 };
Test hello = new Test();
System.out.println(hello.findCommonElement(myArray, myArray2));
}
/**
*
* @param a
* @param b
* @return commonElements
*/
public List<Integer> findCommonElement(int[] a, int[] b) {
List<Integer> commonElements = new ArrayList<Integer>();
for(int i = 0; i < a.length ;i++) {
for(int j = 0; j< b.length ; j++) {
if(a[i] == b[j]) {
//Check if the list already contains the common element
if(!commonElements.contains(a[i])) {
//add the common element into the list
commonElements.add(a[i]);
}
}
}
}
return commonElements;
}
}
发布于 2016-11-16 21:18:40
findCommonElement method
的替代解决方案
public int[] findCommonElement(int[] a, int[] b){
List<Integer> array = new LinkedList<Integer>();
Set<Integer> set = new HashSet<Integer>();
for(int ele:a){
set.add(ele);
}
for(int ele:b){
if(set.contains(ele)){
array.add(ele);
}
}
int[] arr = new int[array.size()];
for(int i = 0; i < array.size();i++){
arr[i] = array.get(i);
}
return arr;
}
发布于 2017-10-16 12:38:35
这是一个O(m+n)解决方案:
static ArrayList<Integer> commonElements(int[] array1, int[] array2) {
int p1 = 0;
int p2 = 0;
ArrayList<Integer> common = new ArrayList<Integer>();
while(true) {
if (array1[p1] == array2[p2]) {
common.add(array1[p1]);
}
if (p1 == array1.length - 1 || p2 == array2.length - 1) break;
if (array1[p1 + 1] < array2[p2 + 1]) {
p1++;
} else {
p2++;
}
}
return common;
}
https://stackoverflow.com/questions/40632887
复制相似问题