This site requires JavaScript, please enable it in your browser!
Greenfoot back
wockrad
wockrad wrote ...

2014/6/20

How many elements of a specific value in an array

wockrad wockrad

2014/6/20

#
Hey, sorry if this is a bit of a basic / stupid question but I'm trying to build a method using the built in java array utilities to find out how many elements of a specific value there are in an array. For example, if the array contained 4,4,4,6 and the argument was 4, I would want it to return 3. I thought I might be able to do it using the binarySearch method but even if I could get it to work it would probably be incredibly clunky and inefficient. I'm hoping there's a built in method for this like the binarySearch or sort ones but if there is one, I cant find it.
lordhershey lordhershey

2014/6/20

#
If the array is sorted you can use a binary search to find one of the instances of the '3', then you just count up and down until you hit non-3's There will be a linear element to this and your worst case running is big O of n. If you could make you array a giant string then you could use regular expressions to find all instances of a pattern, but that would take a lot longer than the first method. You could also do this, go through the array, enter the numbers as keys in a hash table, have the value being the number of times it was seen. Then you can query the hash table (HashMap) when ever you like.
You need to login to post a reply.