From the question itself:
but I want to know a better solution
That makes sense to me in the sense of I know what the words mean, but I'm having a difficult time trying to focus on the problem in the absence of what the OP considers to be suboptimal about the (working) solution that they presented.
Now it could just be that I'm not one of those extremely smart, extremely algorithmically-minded people that would see the working code in that question and begin screaming at their monitor (and I suspect I'm not alone there) and in the absence of that kind of inspiration, I'm kind of lost when it comes to writing the kind of answer that says yes, this question has a place here. The premise of "does improve this code belong" aside, the question seems to be missing a very important component, what the OP thinks is wrong with it in the first place. My initial reaction would also be to close based on not enough information being provided.
Does it have a place? It looks like some answers might be saying it does, but I really hope someone clarifies the question a bit to better match what the answers bring to light for someone else being faced with that kind of problem. That's why folks can (and seem to be) voting to reopen it.
It's kind of hard to give a blanket answer on the on-topic merits of questions that give code and state a clear problem (even if the code works) .. but this one sort of fails at the second half of that out of the gate, and I think that's what folks are reacting to.