如何计算并打印出重复项?
how to count and print out only duplicates?
我知道如何遍历整个数组,但我只需要重复出现的次数。我处于初学者水平,所以只是循环和数组的基本使用。
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");
}
如果你使用的不仅仅是循环和数组,你可以做得更好,但一个简单的算法是使用两个嵌套的 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");
}
}
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);
}
}
我知道如何遍历整个数组,但我只需要重复出现的次数。我处于初学者水平,所以只是循环和数组的基本使用。
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");
}
如果你使用的不仅仅是循环和数组,你可以做得更好,但一个简单的算法是使用两个嵌套的 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");
}
}
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);
}
}