簡體   English   中英

如果數組中已經存在數字,是否會跳過?

[英]Won't skip if number already exists in array?

我目前正在嘗試制作一種顯示次數的方法,該次數存在於數組中。

我的方法是:

public void freq(int[] arr) {
        Arrays.sort(arr);
        String output = "";
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            if (this.helper(arr[i]) == true) {
                i++;
            } else if (this.helper(arr[i]) == false) {
               for (int k : arr) {
                    if (k == arr[i]) {
                        count++;
                    }
                }
                System.out.println("Number of instances to: " + arr[i] + " : " + count);
                count = 0;
            }
        }
    }

helper類用於檢查要檢查的號碼是否已經檢查過。 我正在使用一個arraylist存儲已經檢查過的數字:

private List<Integer> existingInt = new ArrayList<Integer>();

方法助手寫為:

public boolean helper(int i) {
    boolean alreadyExists = false;
    for (int k : existingInt) {
        if (i == k) {
            alreadyExists = true;
            return alreadyExists;
        } else {
            existingInt.add(i);
            alreadyExists = false;
            return alreadyExists;
        }
    }
    return alreadyExists;
}

如果數字存在,則Helper返回一個布爾值,true或false。 此后,我在if語句中檢查它是否返回true或false。 如果為true,則跳過(或至少嘗試):

if (this.helper(arr[i]) == true) {
    i++;
}

簡而言之,我的方法計算整數數組中的出現次數。 如果我的助手方法返回true,則它不做的是跳過檢查。

由於您要對數組進行排序,因此可以執行此操作

    for (int i = 0; i < arr.length;) {
        int count = 1;
        int num = arr[i];
        while(++i < arr.length && arr[i] == num) {
            count++;
        }
        System.out.println("Number of instances to: " + num + " : " + count);
    }

您應該刪除return alreadyExists; 從其他部分。 如果第一項不是i,它將自動返回false。

編輯:您的方法不必要地復雜。 您可以使用以下命令:

public boolean helper(int i) {
    for (int k : existingInt) {
        if (i == k) {
            return true;
        }
    }
    existingInt.add(i);
    return false;
}

更好的是,您可以使用HashSet:

private HashSet<Integer> existingInt = new HashSet<Integer>();

public boolean helper(int i) {
    return existingInt.add(i);
}

您可以通過跟蹤在地圖中找到的數字(作為地圖鍵),並遞增地圖作為顯示該數字的次數來計數發生次數。

唯一的技巧是在您第一次找到該號碼時將其放入地圖中。

我使用由TreeMap實現的SortedMap ,因此在獲取keySet時 ,數字將以升序排列,以獲得良好的輸出。

這是帶有測試main的完整類,可以在默認包中對其進行編譯和運行:

import java.util.SortedMap;
import java.util.TreeMap;

public class Counter
{
    public void printFreq(final int[] numbers)
    {
        // Use a sorted map so our output is ascending.
        final SortedMap<Integer, Integer> numCounts = new TreeMap<>();

        // Count occurrences in the provided numbers
        for (final Integer i : numbers)
        {
            Integer count = numCounts.get(i);   // Get the current count
            if (count == null) count = 0;       // or init it to zero if there isn't one
            numCounts.put(i, ++count);          // Increment count and put it (back) in the map
        }

        // Output the counts
        for (final Integer n : numCounts.keySet())
        {
            System.out.printf("%d : %d\n", n, numCounts.get(n));
        }
    }


    public static void main(String[] args)
    {
        final Counter c = new Counter();
        final int[] nums = { 3, 8, 1, 3, 12, 1, 3, 42, 12, 8 };
        c.printFreq(nums);
    }
}

existingInt為空時,您將不會調用add(i)將新項添加到existingInt 所以existingInt將根據助手代碼始終是空的。

發生這種情況是因為您不會進入for迭代語句。

public boolean helper(int i) {
    if (!existingInt.contains(i)) {
        existingInt.add(i);
        return false;
    }

    return true;
}

實際上,您想對出現次數進行計數的整數數組進行groupBy身份操作。 Java 8 Streams易於使用:

Arrays.stream(array)
    .boxed()
    .collect(groupingBy(
        Function.identity(), 
        counting()
     ));

您將獲得Map<Integer, Long>以及每個元素的計數。

暫無
暫無

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

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