簡體   English   中英

如何在java數組中查找重復項?

[英]How to find duplicates in a java array?

我正在嘗試計算數組中有多少重復項。

例子:

[0, 2, 0] would return 2, [0, 0, 0] would return 3, [0, 1, 2] = 0

到目前為止,當所有三個項目都相等時,我可以使用它,但我不確定為什么它返回的值比兩個項目相同時返回的值少一個。

    int equal = 0;

    for(int i = 0; i < recent.length; i++) {
        for(int j = i; j < recent.length; j++) {
            if(i != j && recent[i].equals(recent[j])) {
                equal++;
            }
        }
    }

您的算法在以下方面存在缺陷:對於數組中的每個元素,您查看該元素之后的所有元素,如果它們碰巧相等,則增加計數器。 但是,當您有 3 個相同的元素時,您將最后一個計數兩次 - 當您為第一個和第二個元素運行內部循環時。 此外,您永遠不會計算第一個元素。

所以它偶然適用於[0, 0, 0]但不適用於其他輸入。

您提供的代碼計算等價,因此每次一個元素等於另一個元素時它都會添加一個。

聽起來您想要的是重復項的數量,這與 (length - 沒有重復項的項數) 相同。 我將后者稱為“uniqueItems”。

我會推薦以下內容:

// set of every item seen
Set<Integer> allItems = new HashSet<Integer>();
// set of items that don't have a duplicate
Set<Integer> uniqueItems = new HashSet<Integer>();

for(int i = 0; i < recent.length; i++) {
    Integer val = i;
    if(allItems.contains(val)) {
        // if we've seen the value before, it is not a "uniqueItem"
        uniqueItems.remove(val); 
    } else {
        // assume the value is a "uniqueItem" until we see it again
        uniqueItems.add(val);
    }
    allItems.add(val);
}
return recent.length - uniqueItems.size();

我認為嵌套循環效率很低。 你應該能夠在 o(n) 而不是 o(n^2) 中做到這一點。

如果您針對以下時間進行計時...

public void run() {
    int[] array = createRandomArray(2000000, 1000000);
    System.out.println(countNumDups1(array));
}


private int[] createRandomArray(int numElements, int maxNumExclusive) {
    int[] array = new int[numElements];
    Random random = new Random();
    for (int i = 0; i < array.length; i++) {
        array[i] = random.nextInt(maxNumExclusive);
    }
    return array;
}

private int countNumDups1(int[] array) {
    Map<Integer, Integer> numToCountMap = new HashMap<>();
    for (int i = 0; i < array.length; i++) {
        Integer key = array[i];
        if (numToCountMap.containsKey(key)) {
            numToCountMap.put(key, numToCountMap.get(key) + 1);
        }
        else {
            numToCountMap.put(key, 1);
        }
    }
    int numDups = 0;
    for (int i = 0; i < array.length; i++) {
        Integer key = array[i];
        if (numToCountMap.get(key) > 1) {
            numDups++;
        }
    }
    return numDups;
}

我認為即使考慮到自動裝箱和對象創建的可怕低效率,您也會發現上述方法要快得多。

下面的代碼可以完美地找到重復項

    int array[] = {1,2,3,4,5,2,3,4,5,3,4,5,4,5,5};

    HashMap<Integer,Integer> duplicates = new HashMap<Integer,Integer>();
    for(int i=0; i<array.length; i++)
    {
        if(duplicates.containsKey(array[i]))
        {
            int numberOfOccurances = duplicates.get(array[i]);
            duplicates.put(array[i], (numberOfOccurances + 1));
        }else{
            duplicates.put(array[i], 1);
        }
    }
    Iterator<Integer> keys = duplicates.keySet().iterator();
    System.out.print("Duplicates : " );
    while(keys.hasNext())
    {
        int k = keys.next(); 
        if(duplicates.get(k) > 1)
        {
            System.out.print(" "+k);
        }
    }

您正在計算具有相等值的索引對的數量。 您聲稱想要的是其中包含多個元素的所有相等元素集的總大小。

我會使用 Map 或類似的東西來計算給定值出現的總數。 最后,迭代鍵值,為每個鍵值添加一次以上出現次數。

int intArray[] = {5, 1, 2, 3, 4, 5, 3, 2};  

String val = "";

int c = 1;

Map<Integer, Integer> nwmap = new HashMap<Integer, Integer>();  

for (int i = 0; i < intArray.length; i++) {

    Integer key = intArray[i];

        if(nwmap.get(key) != null && nwmap.containsKey(key)){

        val += " Duplicate: " +String.valueOf(key)+"\n";

    }else{

        nwmap.put(key, c);

            c++;

    }

}

LOG.debug("duplicate value:::"+val);
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;


public class ArrayDuplicateCount {

    /**
     * @author:raviteja katari
     */
    public static void main(String[] args) {
        int intArray[] = {5, 1,4,4,4,5,1,2,1,2,5,5};  


        //for counting duplicate items
        int c = 0;

        //creating map collection to hold integers as keys and Cont as value
        Map<Integer, Integer> nwmap = new LinkedHashMap<Integer, Integer>();  

        for (int i = 0; i <intArray.length; i++) {

            //Assigning array element to key 
            Integer key = intArray[i];

                //this code checks for elemnt if present updates count value else 
                //put the new Array elemnt into map and increment count

                if(nwmap.containsKey(key)){

                    //updating key value by 1 
                    nwmap.put(key, nwmap.get(key) + 1);

            }else{

                //Adding new array element to map and increasing count by 1
                  nwmap.put(key, c+1);


                   }

                           }
          //printing map
        System.out.println(nwmap);
    }

}

輸出:{5=4, 1=3, 4=3, 2=2}

    public void TotalduplicateNumbers {
    int a[] = {2,8,2,4,4,6,7,6,8,4,5};
    Map<Integer,Integer> m = new HashMap<Integer,Integer>();
    for(int i=0;i<a.length;i++){            

            if(!m.containsKey(a[i]))
            {
                m.put(a[i], 1);
            }
            else
            {
                m.put(a[i], (m.get(a[i])+1));
            }

    }

    for(Integer i:m.keySet()){
        System.out.println("Number "+i+" "+"Occours "+m.get(i)+" time,");
    }
}

我們有一個包含 11 個數字的數組,邏輯是使用這些數字創建一個地圖。 其中地圖的KEYS將是用戶必須輸入的實際數字,而沒有。 該實際編號的出現。 將是該 KEY 的值。 這里, containsKey() 方法檢查映射是否已經包含該鍵並返回布爾值 true 或 false 作為應用。如果它不包含則將該鍵添加到映射中,其對應的值應為 1 否則鍵將已包含在地圖中,因此使用 get() 獲取該鍵的值並將其增加 1。最后打印地圖。

輸出: -

2號出現2次,4號出現3次,5號出現1次,6號出現2次,7號出現1次,8號出現2次,

暫無
暫無

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

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