Optimize to O(logN) time.  fix #1