如何计算Java中数组中的第一个重复值 [英] How to count 1st duplicates value in array in Java

查看:93
本文介绍了如何计算Java中数组中的第一个重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have taken array int[] a = {33,33,5,5,9,8,9,9};
In this array so many values are duplicates means 33 comes twice & 5 also comes twice & 9 comes three times. But I want to count the first value which is duplicate means 33 is first value which comes twice so answer would be 2.

I try:







public class FindFirstDuplicate
{

public static void main(String[] args) {

    int c=0;
    int[] a = {33,33,5,5,9,8,9,9};

    outerloop:
    for(int i = 0; i < a.length; i++)
    {
        for(int j = i+1; j< a.length; j++)
        {
            if(a[i] == a[j])
            {
                System.out.println(a[i]); //Duplicate value
                c++;
                break outerloop;
            }
        }

    }
    System.out.print("Count: "+c);

    }
}
Output: 33 
Count: 1

推荐答案

你几乎就在那里,

1.一个错误,当找到第一个重复,=> c = 2

2.找到第一对后,开始循环计算剩余的重复项。

将以下代码插入原始代码:

You are almost there,
1. One mistake, when the first duplicate found, => c=2
2. Once the first pair found, start a loop to count the remaining duplicates.
Insert the following code to your original one:
// ...
if(a[i] == a[j])
{
    System.out.println(a[i]); //Duplicate value

    // Duplicate means there are at least 2
    c = 2;
    // Once the first pair found, loop to
    // count the number of remaining duplicates
    for(int k = j+1; k < a.length; k++){
        if(a[j] == a[k]){
            c++;
        }
    }
    break outerloop;
// ...


不要在内部循环内部中断,让内部循环完成并计算所有重复项,并在循环检查重复计数后打破循环

don't break inside the inner loop, let inner loop finish and count all the duplicates and after the loop check for duplicate count and break the loop
for(int j = i+1; j< a.length; j++)
{
 if(a[i] == a[j])
 {
     System.out.println(a[i]); //Duplicate value
     c++;   
 }
}
if(c>0) // duplicate found 
{
   break outerloop;
}


这篇关于如何计算Java中数组中的第一个重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆