An efficient quantum algorithm for spectral estimation