如何计算并打印出只重复?

问题描述 投票:2回答:2

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

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
2个回答
2
投票

如果使用不止循环和数组,但一个简单的算法是使用两个嵌套循环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");
    }
}

0
投票
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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.