Identify duplicate numbers in an array

enter image description here

I am dealing with the following problem. I am not looking for anyone to provide me with a solution. I am looking for some recommendations to solve this problem. Here is what I have come up with so far.

I basically tried to put it first (around values ​​that are repeated. However, I get the error out of bounds. I would really appreciate if someone could push me to the right way to code a small algorithm that would handle this problem.

My code (in progress)

import java.util.Random;

public class Test {

    public static void main(String[] args) {

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

        boolean inRun = false;

        for (int i = 0; i < values.length; i++) {

            if (values[i] == values[i + 1] && values[i + 1] < values.length) {
                System.out.print("(");

            }

            System.out.print(values[i]);

        }

    }

}
+4
source share
2 answers

You need to iterate over the entire array, and if it finds a pair, you repeat it again in the while loop until you find a non-empty one.

Example:

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

 boolean inRun = false;

 for (int i = 0; i < values.length; i++) {

     if (i + 1 < values.length && values[i] == values[i + 1] )
     {
         System.out.print("(");
         while (i + 1 < values.length && values[i] == values[i + 1] )
         {
             System.out.print(values[i++]);
         }
         System.out.print(values[i++]);
         System.out.print(")");
     }
     System.out.print(values[i]);

 }

result:

12(55)31243(2222)36(55)631
+4

,

if (values[i] == values[i + 1] && values[i + 1] < values.length) {

i + 1 -

if (i + 1 < values.length && values[i] == values[i + 1]) {

for (int i = 0; i < values.length - 1; i++) { // the length of values - 1 so we can
                                              // get the next value.
+4

Source: https://habr.com/ru/post/1545016/


All Articles