简体   繁体   中英

How to check if elements in an array are sorted according to number of occurences?

I want to check if the elements in an array are sorted according to the number of their occurrences in. This is assuming they are already grouped if elements are the same. int [] y = {7, 7, 7, 8, 8, 5, 5, 5, 5} should return false while int [] y = {5, 5, 5, 5, 7, 7, 7, 8, 8} should return true . There are four 5s, three 7s and two 8s, so it should be arranged that way.

This is what I have so far:

import java.io.*;
import java.util.*;


public class testing2 {

  public static void main(String[] args){
    int [] y = {7, 7, 7, 8, 8, 5, 5, 5, 5};
    System.out.println(isSorted(y));  // should return false

  }

  public static boolean isSorted(int[] y){

    HashMap<Integer,Integer> hash = new HashMap<Integer,Integer>();

    for(int i=0; i<y.length; i++){
      if(hash.containsKey(y[i])){
        hash.put(y[i], hash.get(y[i]) + 1);
      } else {
        hash.put(y[i], 1);
      }
    }
    System.out.println(hash);
    return true;  // code is not complete yet
  }
}

It would print:

{5=4, 7=3, 8=2}
true

So now I have the number of occurrences for each element. What do I do next?

You can solve this in a single pass of the array; here are some hints:

While you are iterating through the array, keep track of the current number (eg 5, 7 or 8) and the quantity . When you finish the next group of number s, compare it the previous number / quantity . Then, return true or false appropriately.

If you prefer keeping your direction of using HashMap , there is one way to continue:

  • Use LinkedHashMap instead, so when you iterate thru the map, you are iterating in the order you put that in the map
  • Iterate thru the map, and see if each entry is having count < prev entry. Pseudo Code:

     int prevCount = MAX_INT; for (entry : map) { currentCount = entry.getValue() if (currentCount > prevCount) { return false } prevCount = currentCount } return true; 

Or, you can have one single-pass on the array (pseudo-code):

 prevCount = MAX_INT
 currentCount = 0;
 for (i = 0...array.length) {
     increment currentCount 

     // if i points to last number in group
     if (i is the last element of array, OR
             next element is not equals to current element) {
         if currentCount > prevCount {
             return false;
         }
         prevCount = currentCount;
         currentCount = 0;
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM