from leetcode master, there is an even better solution