开发者

how will I find odd elements from two arrays

I have one array

int a[] = {1,2,3}开发者_如何学JAVA;
int b[] = {1,2};

how will I find the odd element in array


    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+",");

I put two answers for the voting, the previous is nested loops and might be slow for very long arrays. In the next solution some might dont prefer the TreeSet.


    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);


If you are talking about Set Comparisons, have a look at java-is-there-an-easy-quick-way-to-and-or-or-xor-together-sets

This SO question was talking in terms of the Set interface, but the List interface also inherits the relevant methods from Collection, so copying your arrays to ArrayList objects makes it easy.

If you want to keep it purely at the native array level, you might want to do something like:

 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;
 }


Make a loop for each array item. Those for which item & 1 == 1 are odd.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜