本文介绍了如何计算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
推荐答案
// ...
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;
// ...
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中数组中的第一个重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!