簡體   English   中英

是否有可能找出一個值在數組列表中是否存在兩次?

[英]Is it possible to find out if a value exists twice in an arraylist?

我有一個整數數組列表..

ArrayList <Integer> portList = new ArrayList();

我需要檢查是否已經輸入了兩次特定的整數。 這在Java中可能嗎?

您可以使用類似這樣的東西來查看特定值出現的次數:

System.out.println(Collections.frequency(portList, 1));
// there can be whatever Integer, i put 1 so you can understand

並檢查特定值是否不止一次存在,您可以使用以下內容:

if ( (Collections.frequency(portList, x)) > 1 ){
    System.out.println(x + " is in portList more than once ");
} 

這將告訴您ArrayList是否至少有兩個相同的值

int first = portList.indexOf(someIntValue);
int last  = portList.lastIndexOf(someIntValue);
if (first != -1 && first != last) {
    // someIntValue exists more than once in the list (not sure how many times though)
}

**編輯**

如果您真的想知道給定值有多少重復項,則需要遍歷整個數組。 像這樣的事情:

/**
 * Will return a list of all indexes where the given value
 * exists in the given array. The list will be empty if the
 * given value does not exist at all.
 *
 * @param List<E> list
 * @param E value
 * @return List<Integer>    a list of indexes in the list
 */
public <E> List<Integer> collectFrequency(List<E> list, E value) {
   ArrayList<Integer> freqIndex = new ArrayList<Integer>();
   E item;
   for (int i=0, len=list.size(); i<len; i++) {
       item = list.get(i);
       if ((item == value) || (null != item && item.equals(value))) {
           freqIndex.add(i);
       }
   }
   return freqIndex;
}

if (!collectFrequency(portList, someIntValue).size() > 1) {
    // duplicate value
}

或者干脆

if (Collections.frequency(portList, someIntValue) > 1) {
    // duplicate value
}

如果你想用一種方法來做到這一點,那么不。 但是,如果您需要簡單地找出它在列表中至少存在一次,則可以分 2 個步驟。 你可以做

int first = list.indexOf(object)
int second = list.lastIndexOf(object) 
//Don't forget to also check to see if either are -1, the value does not exist at all.
if (first == second) {
    // No Duplicates of object appear in the list
} else {
    // Duplicate exists
}

我知道這是一個老問題,但既然我在這里尋找答案,我想我會分享我的解決方案

public static boolean moreThanOnce(ArrayList<Integer> list, int searched) 
{
    int numCount = 0;

    for (int thisNum : list) {
        if (thisNum == searched) numCount++;
    }

    return numCount > 1;
}
Set portSet = new HashSet<Integer>();
portSet.addAll(portList);
boolean listContainsDuplicates = portSet.size() != portList.size();

我使用以下解決方案找出 ArrayList 是否不止一次包含一個數字。 此解決方案與上面user3690146列出的解決方案非常接近,但根本不使用輔助變量。 運行它后,您會收到“該號碼被多次列出”作為返回消息。

public class Application {

    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<Integer>();

        list.add(4);
        list.add(8);
        list.add(1);
        list.add(8);

        int number = 8;

        if (NumberMoreThenOnceInArray(list, number)) {
            System.out.println("The number is listed more than once");
        } else {
            System.out.println("The number is not listed more than once");
        }
    }

    public static boolean NumberMoreThenOnceInArray(ArrayList<Integer> list, int whichNumber) {

        int numberCounter = 0;

        for (int number : list) {
            if (number == whichNumber) {
                numberCounter++;
            }
        }

        if (numberCounter > 1) {
            return true;
        }

        return false;
    }

}

這是我的解決方案(在 Kotlin 中)

    // getItemsMoreThan(list, 2) -> [4.45, 333.45, 1.1, 4.45, 333.45, 2.05, 4.45, 333.45, 2.05, 4.45] -> {4.45=4, 333.45=3}
    // getItemsMoreThan(list, 1)->  [4.45, 333.45, 1.1, 4.45, 333.45, 2.05, 4.45, 333.45, 2.05, 4.45] -> {4.45=4, 333.45=3, 2.05=2}
    fun getItemsMoreThan(list: List<Any>, moreThan: Int): Map<Any, Int> {
        val mapNumbersByElement: Map<Any, Int> = getHowOftenItemsInList(list)
        val findItem = mapNumbersByElement.filter { it.value > moreThan }
        return findItem
    }

    // Return(map) how often an items is list.
    // E.g.: [16.44, 200.00, 200.00, 33.33, 200.00, 0.00] -> {16.44=1, 200.00=3, 33.33=1, 0.00=1}
    fun getHowOftenItemsInList(list: List<Any>): Map<Any, Int> {
        val mapNumbersByItem = list.groupingBy { it }.eachCount()
        return mapNumbersByItem
    }

通過看問題,我們需要找出一個在一個ArrayList中是否存在兩次 所以我相信我們可以通過下面的簡單檢查來減少“遍歷整個列表只是為了檢查該值是否只存在兩次”的開銷

public boolean moreThanOneMatch(int number, ArrayList<Integer> list) {

    int count = 0;
    for (int num : list) {
        if (num == number) {
            count ++ ;
            if (count == 2) {
                return true;
            }
        }
    }
    return false;
}

暫無
暫無

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

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