簡體   English   中英

如何在JAVA中合並數組而不重復並且不使用內置函數?

[英]How to merge arrays in JAVA without duplicates and not using built-in functions?

可以說我有兩個整數數組,我想將它們合並而不重復。

我知道我可以在Set中添加它們,然后可以將它們檢索為arraylist。

但是不使用任何內置函數怎么辦?

由於數組的元素順序不同,因此取決於您要如何合並它們。

您可以添加一個(另一個)(最簡單),也可以“壓縮”它們(一個元素來自A,然后一個元素來自B,然后另一個元素來自A,依此類推)。

主要問題是您必須檢查新數組中是否已包含要添加的值。 使用內置函數和實現(例如Set )最簡單。 有Set實現,例如HashSet,可為您提供恆定時間的性能以查找值並將其插入。

我真的建議您以“通常”的方式進行操作,而不要嘗試重新發明輪子。

我覺得這很可讀:

 static int[] merge(int[] a, int[] b) {
     Set<Integer> set = new HashSet<>(Arrays.asList(a));
     set.addAll(Arrays.asList(b)); // skips duplicate as per Set implementation

     return set.toArray(new int[0]);
 }

這同時使用了重復方法和內置方法,但是很簡潔。

private Set<Integer> mergeWithoutDuplicates(int[] a, int[] b) {
  Set<Integer> set1= new HashSet<Integer>(a.length+b.length);
  for (int i=0; i<a.length; i++) {
      set1.add(a[i]);
  }
  for (int i=0; i<b.length; i++) {
      set1.add(b[i]);
  }
  return set1;

}

此功能應達到您的目的

很多代碼,但這是一個示例。

    try{
        int[] a = {1,2,3,4,5,6,7};
        int[] b = {5,6,7,8,9,10};
        int[] c = new int[a.length+b.length];
        int[] fin = new int[a.length+b.length];
        int i = 0;
        for(int j : fin){
            fin[i++] = -1;
        }
        i = 0;
        for(int j : a){
            c[i++] = j;
        }
        for(int j : b){
            c[i++] = j;
        }
        boolean check = false;
        for(int j = 0,k = 0; j < c.length; j++){
            for(int l : fin){
                if( l == c[j] )
                    check = true;
            }
            if(!check){
                fin[k++] = c[j];
            } else check = false;
        }

    } catch(Exception ex){
        ex.printStackTrace();
    }

暫無
暫無

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

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