My solution is as same as yours, but the first time I submitted it returning TLE. After reading this post, I tried again, and got Accepted, miraculous.