java - How to check if elements in an array are sorted according to number of occurences? -
i want check if elements in array sorted according number of occurrences in. assuming grouped if elements 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 4 5s, 3 7s , 2 8s, should arranged way.
this have 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 not complete yet } }
it print:
{5=4, 7=3, 8=2} true
so have number of occurrences each element. do next?
you can solve in single pass of array; here hints:
while iterating through array, keep track of current number
(e.g. 5, 7 or 8) , quantity
. when finish next group of number
s, compare previous number
/quantity
. then, return true or false appropriately.
Comments
Post a Comment