Write a Java program to find the first array element whose value is repeated an integer array?

Java 8Object Oriented ProgrammingProgramming

To find the first non-repeating number in an array −

  • Construct count array to store count of each element in the given array with same length and with initial value 0 for all elements.
  • Compare each element in the array with all other elements, except itself.
  • If match occurs increment its value in the count array.
  • Get the index of the first non-zero element in the count array and print the element in the input array at this index.

Example

import java.util.Arrays;
public class NonRpeatingArray {
   public static void main(String args[]) {
      int array[] = {114, 225, 669, 996, 336, 6547, 669, 225, 336, 669, 996, 669, 225 };
      System.out.println("");
      //Creating the count array
      int countArray[] = new int[array.length];
      for(int i=0; i<array.length; i++) {
         countArray[i] = 0;
      }
      for(int i=0; i<array.length; i++) {
         for(int j=0; j<array.length;j++) {
            if(i!=j && array[i]==array[j]) {
               countArray[i]++;
            }
         }
      }
      System.out.println(Arrays.toString(countArray));
      //First non-repeating element in the array
      for(int i=0; i<array.length; i++) {
         if(countArray[i]!=0) {
            System.out.println(array[i]);
            break;
         }
      }
   }
}

Output

[0, 2, 3, 1, 1, 0, 3, 2, 1, 3, 1, 3, 2]
225
raja
Published on 02-Aug-2019 12:56:21
Advertisements