簡體   English   中英

如何檢查數組中的元素是否在另一個數組中重復。 所有這些數組都在多維數組中?

[英]How to check if an element from an array is being repeated in another array. All these arrays are inside of a Multidimensional array?

基本上我循環遍歷每個數組中的每個元素,試圖找到一個元素也是另一個數組中的元素,如果有一個元素在另一個數組中重復,我想打印出該元素以及停止循環 簡而言之,這就是我所擁有的:

def list = [[2,3,5,10,13], [12,23,9,8], [34,11,14,15,67,28,5], [7,23,67,27,30,33]]

重要信息 :元素永遠不會在同一個數組中出現兩次

我需要遍歷每個數組的元素並將其與其他數組中的其他元素進行比較,如果有一個元素正在重復(例如:5 - 這個數字在array1和array3中重復)那么我的循環應該是STOP 。 我被困在這一段時間了。 有誰知道如何在Groovy中解決這個問題? 非常感謝提前!

def list = [
    [2,3,5,10,13], 
    [12,23,9,8], 
    [34,11,14,15,67,28,5], 
    [7,23,67,27,30,33]
]

list.flatten().countBy { it }.findResult { k, v -> v > 1 ? k : null }

聲明Bidimensional-Array

 Integer [][]a = {{2,3,5,10,13}, {12,23,9,8}, {34,5,11,14,15}, {7,23,67,27,30,33}};

尋找集合之間相交的數字

boolean numberFound = false;
int number=0;
for (int i = 0; i < a.length && !numberFound; i++){
    for (int j = i+1; j < a.length && !numberFound; j++) {
        HashSet<Integer> intersection = new HashSet<Integer>(Arrays.asList(a[i]));
        intersection.retainAll(Arrays.asList(a[j]));
        if(intersection.size()>0){
            numberFound = true;
            number = intersection.iterator().next().intValue();
        }
    }
}

印花

if(numberFound){
    System.out.println("Number found is: " +number);
} else{
    System.out.println("Number not found");
}

UPDATE

如果我們確定一個元素永遠不會在同一個數組中出現兩次,我們就可以使用這個代碼:

Entry<Integer, Long> entry = Arrays.stream(a)
 .flatMapToInt(Arrays::stream)
   .boxed()
     .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
       .entrySet()
        .stream()
         .filter(s -> s.getValue() > 1)
          .findAny()
           .orElse(null);

if(entry == null){
 System.out.println("Number not found");
}else {
 System.out.println("Number found: " + orElse.getKey());
}
int[][] list = {{2,3,5,10,13}, {12,23,9,8}, {34,11,14,15,67,28,5}, {7,23,67,27,30,33}};
HashSet<Integer> seenItems = new HashSet<>();
for(int i = 0; i < list.length; i++) {
    int[] l = list[i];
    for(int j = 0; j < l.length; j++) {
        int itemToCheck = l[j];
        if (seenItems.contains(itemToCheck)) {
            System.out.println("We've already seen " + itemToCheck);
            return;
        } else {
            seenItems.add(itemToCheck);
        }
    }
 }

暫無
暫無

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

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