How to check if all duplicates in an array are grouped

I want to check if all similar integers are grouped in an array or list. {2, 2, 5, 5, 5, 1, 7, 7, 5, 7}must give false. I {2, 2, 5, 5, 5, 1, 7, 7, 7}have to give it so far true. This is what I have and prints truewhen it should be false:

public class testing1 {

  public static void main(String[] args){
    int [] x = {2, 2, 5, 5, 5, 1, 7, 7, 5, 7};
    System.out.println(isGrouped(x));

  }

  public static boolean isGrouped(int[] x){
    for(int i = 0; i < x.length; i++){
      for(int j = i + 1; j < x.length; j++){
        if(x[i] == x[j]) 
          return true;
      }
    }
    return false;
  }
}
+4
source share
4 answers

, , , , . , 2 . , . , .

:

public class testing1 {

  public static void main(String[] args){
    int [] x = {2, 2, 5, 5, 5, 1, 7, 7, 5, 7};
    System.out.println(isGrouped(x));
  }

  public static boolean isGrouped(int[] x){

      int prev = x[0] ;

    Hashtable<Integer, Integer> hashtable = 
              new Hashtable<Integer, Integer>();
    hashtable.put(x[0], 0);
    for (int i = 1 ; i < x.length ; i ++)
    {
        if (hashtable.get(x[i]) != null && prev == x[i]){
            hashtable.put(x[i], hashtable.get(x[i]) + 1);
        }

        else if (hashtable.get(x[i]) != null && prev != x[i]){
            return false;
        }

        else{
            hashtable.put(x[i], 0);
        }
        prev = x[i];
    }
    return true ;
    }

}

. , :)

+1

,

for(int i = 0; i < x.length; i++){
  for(int j = i + 1; j < x.length; j++){
    if(x[i] == x[j]) 
      return true;
  }
}

true, ( 2,2). , , , isGrouped, true.

, , , , .

, true , . , .

+2

, .

  • , /
  • , .

, ?

  • ,
  • ,
  • , , ,
  • .
+2

, , , , true.

:

  • ( set, )
  • - , true, false

:

for (int i = 1; i < x.length; i++) {
    if (x[i-1] != x[i]) {
        newArr.add(x[i]);
    }
}

:

Set<Integer> set = new HashSet<>();
for (int i = 0; i < x.length; i++){
    set.add(x[i]);
}
// create array from the set

.

+1

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


All Articles