繁体   English   中英

integer 数组中重复值的数量

[英]Number of repeated values in an integer array

我需要一个 function 或方法来查找在一个值中重复的值的数量。 我不是在寻找重复的数字,或者它们重复的次数,而只是一般重复的数字数量。 这可能听起来令人困惑,所以这里有一个例子:

int[] anArray = { 
    1, 2, 3,
    4, 3, 1, 
    7, 2, 9, 1
};

数字 1 有多个实例,2 和 3 也是如此。
因此我的 output 应该是“连续值有 3 种情况”
这是我到目前为止所拥有的:

    int x;
    int i = 0;
    int[] array = new int[10];

    do {
      x = input.nextInt();
      array[i] = x;
      i++;
    } while(x!=0);

在循环之外,我需要能够 output 重复值的数量。 这是 while 循环的做法,因此我不能使用 for 循环。

您可以使用以下伪代码:

  • 给定一个数字数组
  • 按数字对所有值进行分组
  • 过滤所有重复值
  • 打印所有重复的数字

实现如下:

        int[] anArray = { 1, 2, 3, 4, 3, 1, 7, 2, 9, 1 };
        Arrays.stream(anArray).boxed()
            .collect(Collectors.groupingBy(Integer::intValue))
            .values().stream().filter(l->l.size()>1)
            .forEach(numbers -> System.out.println(numbers.get(0)));

output 将是:

1
2
3   

如果您必须使用while循环,那么您可以尝试以下使用 Arrays.sort function 的简单算法:

int getRepeatedElements(int[] array){
    //Sort the numbers in ascending order
    java.util.Arrays.sort(array);

    //Strategy: Store the first occurrence of each number and then move to the next element to see if it is repeated
    int currentElement = array[0];
    int repeatedCount = 0;
    int i = 1;
    boolean alreadyCounted = false;

    while(i < array.length){
        if(currentElement == array[i]){
            //Found a repeated element!
            if(!alreadyCounted){
                repeatedCount++;
                alreadyCounted = true;
            }
        }
        else{
            //New element found
            currentElement = array[i];
            alreadyCounted = false;
        }
        i++; //Move to the next element
    }
    return repeatedCount;
}

尝试这个:

import java.util.*;

public class Main {

    public static void main(String[] args) {
        int[] anArray = { 1, 2, 3, 4, 3, 1, 7, 2, 9, 1, 1, 2 };
        java.util.Arrays.sort(anArray);
        System.out.println(Arrays.toString(anArray));
        int countedElement = anArray[0]; // has the checked element
        int count = 0;
        for (int i = 1; i < anArray.length - 1; i++) {
            if (countedElement == anArray[i] && anArray[i] != anArray[i + 1]) {
                count++;
            } else {
                countedElement = anArray[i];
            }
        }
        System.out.println(count);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM