【问题标题】:how to count and print out only duplicates?如何仅计算和打印重复项?
【发布时间】:2016-11-18 21:06:51
【问题描述】:

我知道如何遍历整个数组,但我只需要重复出现的次数。我是初学者,所以只是循环和数组的基本使用。

int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};

for (int i = 0; i < array.length; i++) {
    int count = 0;
    for (int j = 0; j < array.length; j++) {
        count++;   
    }
    System.out.println(array[i] + "\toccurs\t" + count + "X");
}

【问题讨论】:

标签: java arrays find-occurrences


【解决方案1】:

如果你不仅仅使用循环和数组,你可以做得更好,但一个简单的算法是使用两个嵌套的for 循环,并在其中放置一个if 语句,当找到重复项时递增一个计数器。

int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};

for (int i = 0; i < array.length - 1; i++) {
    int count = 1;
    for (int j = i + 1; j < array.length; j++) {
        if (array[i] == array[j]) {
            count++;
        }
    }
    if (count > 1) {
        System.out.println(array[i] + "\toccurs\t" + count + " times");
    }
}

【讨论】:

    【解决方案2】:
    using System;
    
    public class Exercise34
    {
        public static void Main()
        {
            int[] a = { 3,4,5,6,7,8,3,4,5,6,7,8,9,9};
            int n = a.Length-1;
            int dupcounter = 0;
            for (int i = 0; i < n; i++)
            {
                int counter = 0;
                for (int j = i + 1; j <= n; j++)
                {
                    if (a[i] == a[j])
                    {
                        counter++;
                        n--;
                        if (counter == 1)
                        {
                            dupcounter++;
                            Console.WriteLine(a[i]);                        
                        }
                        for (int k = j; k <= n; k++)
                        {
                            a[k] = a[k + 1];
                        }
                    }
                }
            }
            Console.WriteLine(dupcounter);
        }
    }
    

    【讨论】:

    • 代码一旦找到数字的复制,就会尝试减小数组的大小。如果我正确理解了这个问题,我们都必须寻找重复出现的次数,而不是它出现的次数。删除所有出现后,我们将迭代直到减少“N”次并打印所有数字。 (注:无需整理)
    猜你喜欢
    • 2012-05-16
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 2017-08-20
    相关资源
    最近更新 更多