Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Duplicate Counting in an Array Write a method that takes an array of size N >= 2

ID: 675497 • Letter: D

Question

Duplicate Counting in an Array Write a method that takes an array of size N >= 2, and contains integers from 1 to n-1 (inclusive.) One of the elements is repeated. The method should return the value (an integer) of the element that is repeated for JAVA.

this is code i currently have but its not working and i could use some help with it.

package com.java2novice.argos;

public class MyClass

{

pubblic static int[] removeDuplicates(int[] input){

int j=0;

int i=1;

if(input.length<2){

return input;

}

while(i<input.length){

if(input[i]==input[j]){

i++;

} else{

input[++j]=input[i++];

}

}

int[] output=new int[j+1];

for(int k=0;k<output.length;k++){

output[k]=input[k];

}

return output;

}

public static void main(String args[])

int[] input1={1,2,3,4,3,4,5,6}

int[] output=removeDuplicates(input1);

for(int i:output){

System.out.println(i+" ");

}

}

Explanation / Answer

//Your whole apparoach is wrong. It is said only one element is repeated and the return value is not the array after the duplicates are removed it is the repeated number


public class MyClass {

   public static void main(String args[])
   {
       int[] input={1,2,3,4,5,6,1};
       System.out.println(getrepeated(input));
   }

   private static int getrepeated(int[] input) {
       // TODO Auto-generated method stub
       int n = input.length;
       int i,sum=0,ct=0;
       if(n<2)
       {
           return -1;
       }
       ct = ((n-1)*n)/2; // Sum of the number 1,2,3...n-1
       for(i=0;i<n;i++)
           sum+=input[i];
       //sum = (1+2+3... n-1) + (repeated number)
       return sum-ct;
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote