1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class Solution { private Map<Integer, Integer> map = new HashMap<>();
public int getKth(int lo, int hi, int k) { if (lo > hi) { return 0; } int[][] dp = new int[hi - lo + 1][2]; for (int i = lo; i <= hi; i++) { dp[i - lo][0] = i; dp[i - lo][1] = getWeight(i); } Arrays.sort(dp, (a, b) -> { if (a[1] == b[1]) { return a[0] - b[0]; } else { return a[1] - b[1]; } }); return dp[k - 1][0]; }
private int getWeight(int num) { if (num == 1) { return 0; } if (map.containsKey(num)) { return map.get(num); } int res = 0; if ((num & 1) == 1) { res = getWeight(num * 3 + 1) + 1; } else { res = getWeight(num / 2) + 1; } map.put(num, res); return res; } }
|