我如何从两个数组中找到奇数元素

时间:2009-12-21 09:06:12

标签: java arrays

我有一个数组

int a[] = {1,2,3};
int b[] = {1,2};

如何在数组中找到奇数元素

4 个答案:

答案 0 :(得分:2)

    int[] longArray = { 1, 3, 2 };
    int[] shortArray = { 1, 2 };

    //Check which array is longer, if b longer than a then swap

    for (int x:longArray){
        set.add(x);
    }
    for (int x:shortArray){
        if (set.contains(x))
           set.remove(x);
    }
    //odd numbers
    for (Object i:set.toArray())
        System.out.println(i+",");

我为投票放了两个答案,前面是嵌套循环,对于很长的数组可能会很慢。有些人可能不喜欢TreeSet。

答案 1 :(得分:1)

    int[] longArray = { 1, 3, 2 };
    int[] shortArray = { 1, 2 };

    //Check which array is longer, if b longer than a then swap

    boolean found = false;
    int odd = 0;

    for (int i : longArray) {
        for (int j : shortArray) {
            if (i == j)
                found = true;
        }
        if (!found)
            odd = i;
        found = false;
    }
    System.out.println(odd);

答案 2 :(得分:0)

为每个数组项创建一个循环。 item & 1 == 1奇怪的那些。

答案 3 :(得分:0)

如果您正在谈论Set Comparisons,请查看java-is-there-an-easy-quick-way-to-and-or-or-xor-together-sets

这个SO问题是根据Set接口进行讨论,但List接口也从Collection继承了相关的方法,因此将数组复制到ArrayList对象变得容易。

如果您想将其完全保留在本机数组级别,您可能需要执行以下操作:

 public int[] findOddElement(int[] fromArray, int[] secondArray){
  int[] result = new int[fromArray.length];
  int resPointer = 0;
  for (int i = 0;i < fromArray.length;i++){
   boolean notFound = true;
   for (int j = 0; j < secondArray.length; j++) {
    if (fromArray[i] == secondArray[j]) {
     notFound = false;
     break;
    }
   }
   if (notFound){
    result[resPointer] = fromArray[i];
    resPointer++;
   }
  }
  if (resPointer > 0 && resPointer < fromArray.length ) {
   int[] newResult = new int[resPointer];
   for (int i = 0;i < resPointer; i++) {
    newResult[i] = result[i];

   }
   return newResult;
  }
  return result;
 }