program question:
Write a code to find duplicate elements in array and total count of duplicate elements.
eg. arr={5,3,4,6,7,5,3,2,1}
Duplicate elements:- 5,3
Total duplicate count:- 2
solution:
package com.shashi;
import java.util.ArrayList;
public class DuplicateCount {
public static void main(String []args)
{
int arr[]={5,3,4,6,7,5,3,2,1,1};
int count=0;
ArrayList<Integer> list=new ArrayList<Integer>();
ArrayList<Integer> dup=new ArrayList<Integer>();
for(int ar:arr)
{
if(!list.contains(ar))
{
list.add(ar);
}
else
{
dup.add(ar);
count++;
}
}
//printing data
System.out.print("duplicate elements are:"+dup+"\n");
System.out.print("Number of such elements are:"+count);
}
}
output:
duplicate elements are:[5, 3, 1]
Number of such elements are:3
Explanation:
--I created an arraylist that stores that stores duplicate elements.
logic
move:
if(arraylist element already presented add the element to duplicate)
increase count value
repeat move;
Write a code to find duplicate elements in array and total count of duplicate elements.
eg. arr={5,3,4,6,7,5,3,2,1}
Duplicate elements:- 5,3
Total duplicate count:- 2
solution:
package com.shashi;
import java.util.ArrayList;
public class DuplicateCount {
public static void main(String []args)
{
int arr[]={5,3,4,6,7,5,3,2,1,1};
int count=0;
ArrayList<Integer> list=new ArrayList<Integer>();
ArrayList<Integer> dup=new ArrayList<Integer>();
for(int ar:arr)
{
if(!list.contains(ar))
{
list.add(ar);
}
else
{
dup.add(ar);
count++;
}
}
//printing data
System.out.print("duplicate elements are:"+dup+"\n");
System.out.print("Number of such elements are:"+count);
}
}
output:
duplicate elements are:[5, 3, 1]
Number of such elements are:3
Explanation:
--I created an arraylist that stores that stores duplicate elements.
logic
move:
if(arraylist element already presented add the element to duplicate)
increase count value
repeat move;
No comments:
Post a Comment