Lintcode solution in Java.