I was proud that I figured out the answer myself but then I read the question again and noticed the signature:
Write a method findDuplicates that will return an array consisting of all duplicate values that were found in a given array. For example, if given an array consisting of the values {1, 7, 3, 7, 3, 4, 1, 3, 2} the method would return an array consisting of the values {1,7,3}.
public static int[] findDuplicates(int[] naVals)
What I have:
public static int findDuplicates(int[]
naVals)
{
Arrays.sort(naVals);
for (int i = 1; i < naVals.length; i++)
{
if (naVals[i] == naVals[i-1])
{
return naVals[i];
}
}
return -1;
}
}
and the test method:
@Test
public void testQ7()
{
int[] naExpected1 = {1, 7,
3};
int[] naTest1 = { 1,
7,3,7,9,4,1,3,7, 3,2};
assertArrayEquals(naExpected1,
Q7.findDuplicates(naTest1));
}
public static int[] findDuplicates(int[] naVals)
{
ArrayList<Integer> duplicates=new
ArrayList<Integer>();
for(int i=0;i<naVals.length;i++)
{
for(int
j=i+1;j<naVals.length;j++)
if(naVals[i]==naVals[j] &&
!(duplicates.contains(naVals[i]))) //element is not present in
arraylist
duplicates.add(naVals[i]); //add
duplicate element
}
//convert ArrayList to array
int[] a=new int[duplicates.size()];
for(int i=0;i<duplicates.size();++i)
a[i]=duplicates.get(i);
return a;
}
Get Answers For Free
Most questions answered within 1 hours.