Il mio maestro mi ha dato il compito successivo:Contare il numero di occorrenze di un numero in un array ordinato
On a sorted array, find the number of occurrences of a number.
The complexity of the algorithm must be as small as possible.
Questo è quello che ho pensato:
public static int count(int[] a, int x)
{
int low = 0, high = a.length - 1;
while(low <= high)
{
int middle = low + (high - low)/2;
if(a[middle] > x) {
// Continue searching the lower part of the array
high = middle - 1;
} else if(a[middle] < x) {
// Continue searching the upper part of the array
low = middle + 1;
} else {
// We've found the array index of the value
return x + SearchLeft(arr, x, middle) + SearchRight(arr, x, middle);
}
}
return 0;
}
SearchLeft
e SearchRight
iterarlo array, fino a quando il numero non viene visualizzato.
Non sono sicuro di aver raggiunto la scrittura del codice più veloce per questo problema e vorrei vedere altre opinioni.
Edit: Dopo qualche aiuto da commenti e risposte, questo è il mio tentativo in corso:
public static int count(int[] array, int value)
{
return SearchRightBound(array, value) - SearchLeftBound(array, value);
}
public static int SearchLeftBound(int[] array, int value)
{
int low = 0, high = array.length - 1;
while(low < high)
{
int middle = low + (high - low)/2;
if(array[middle] < value) {
low = middle + 1;
}
else {
high = middle;
}
}
return low;
}
public static int SearchRightBound(int[] array, int value)
{
int low = 0, high = array.length - 1;
while(low < high)
{
int middle = low + (high - low)/2;
if(array[middle] > value) {
high = middle;
}
else {
low = middle + 1;
}
}
return low;
}
[In C++, ma per il resto per lo più applicabili.] (Http://stackoverflow.com/a/10935920/179910) –
In sostanza, sì. Ci sono due problemi che vedo, a) devi aggiungere 1 nel caso in cui l'obiettivo si verifichi, b) ottieni un valore di ritorno negativo se l'obiettivo non si verifica. –
Non usare il tag dei compiti a casa è deprecato – Woot4Moo