簡體   English   中英

多數組的常見元素,但不使用列表

[英]Common elements of muiltiple arrays but not using Lists

有沒有辦法我可以在數組中返回2個或更多數組的公共元素? 我知道在列表下有一些方法可以做到,但是有沒有辦法只使用數組呢? 因為創建了一個名為OrderedIntList的數組,所以我做了自己的get和length btw。

例如:

1,3,5

1,6,7,9,3

1,3,10,11

結果:1,3

我試過了,它輸出兩個數組之間的公共元素,而不是全部。 我知道有什么問題,但是我不知道如何使它正常工作:(

//返回輸入數組的公共元素

public static OrderedIntList common(OrderedIntList ... lists){ 

int[] list = new int[10];

for(int x = 1; x <= lists.length -1; x++){

  for(int q = 0; q < lists[0].length()-1; q++) {

    for(int z = 0; z < lists[x].length(); z++) {

      if (lists[0].get(q)==lists[x].get(z)){
         list[q] = lists[0].get(q);
                  }
              }
          }
      }

 OrderedIntList newlist = new OrderedIntList(list);     

 return newlist;
  }

您可以使用

org.apache.commons.collections.CollectionUtils.intersection(java.util.Collection a, java.util.Collection b)

獲取兩個列表的交集(兩個列表中都存在元素)

並將您的數組作為Collection傳遞:java.util.Arrays.asList(Object [] a);

但是,充其量來說,處理數組很乏味。 您應該考慮為什么不想使用收藏夾...

這可能是解決問題的簡單算法...

  1) Instantiate an instance variable of type array called "commonElements" pointing to the elements of the first Array. At the beginning these are your common elements. 2) Create a method call getCommonElements(int[] commonElements, int[] newList). This method manipulates the commonElements array to leave it with only the common elements between the two. (ps Use a temporary array to achieve this if you find it easier) 3) Iterate over all the arrays present in "lists" starting from the second array. 4) call the method at point 2 for each array . 

對您而言,所有困難的部分是實現一種方法,該方法使給定的2個數組查找公共元素!

作為部分回答,您可能會通過完全重新實現OrderedIntList的方式來做很多工作,因為ArrayList和朋友已經通過Collections類進行了排序。

import java.util.Collections;
public class OrderedIntList extends ArrayList<Integer> {
  @override // to effect sorted inserts
  public void add(Integer i) {
    this.add(i);
    Collections.sort(this);
    // done.
  }
}

希望對純數組執行此操作是一個不錯的練習,但是這樣做會更好,您可以使用快速排序(無法在沒有獲得一百萬個結果的情況下通過網絡搜索該Java實現的網絡搜索)或插入排序(同樣可通過網絡搜索),並遵循相同的食譜。

每當您將數字推入數組時:

  1. 猜數字在哪里(盡管這是可選的),
  2. 輸入號碼,
  3. 如果您知道自己的猜測並不完美,請重新排列數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM