Leetcode solution in Java