|
| 1 | +/** |
| 2 | + * 1387. Sort Integers by The Power Value |
| 3 | + * https://leetcode.com/problems/sort-integers-by-the-power-value/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * The power of an integer x is defined as the number of steps needed to transform x into |
| 7 | + * 1 using the following steps: |
| 8 | + * - if x is even then x = x / 2 |
| 9 | + * - if x is odd then x = 3 * x + 1 |
| 10 | + * |
| 11 | + * For example, the power of x = 3 is 7 because 3 needs 7 steps to become 1 |
| 12 | + * (3 --> 10 --> 5 --> 16 --> 8 --> 4 --> 2 --> 1). |
| 13 | + * |
| 14 | + * Given three integers lo, hi and k. The task is to sort all integers in the interval |
| 15 | + * [lo, hi] by the power value in ascending order, if two or more integers have the same |
| 16 | + * power value sort them by ascending order. |
| 17 | + * |
| 18 | + * Return the kth integer in the range [lo, hi] sorted by the power value. |
| 19 | + * |
| 20 | + * Notice that for any integer x (lo <= x <= hi) it is guaranteed that x will transform |
| 21 | + * into 1 using these steps and that the power of x is will fit in a 32-bit signed integer. |
| 22 | + */ |
| 23 | + |
| 24 | +/** |
| 25 | + * @param {number} lo |
| 26 | + * @param {number} hi |
| 27 | + * @param {number} k |
| 28 | + * @return {number} |
| 29 | + */ |
| 30 | +var getKth = function(lo, hi, k) { |
| 31 | + const powerValues = new Map(); |
| 32 | + const numbers = Array.from({ length: hi - lo + 1 }, (_, i) => lo + i); |
| 33 | + |
| 34 | + numbers.sort((a, b) => { |
| 35 | + const powerA = getPower(a); |
| 36 | + const powerB = getPower(b); |
| 37 | + return powerA === powerB ? a - b : powerA - powerB; |
| 38 | + }); |
| 39 | + |
| 40 | + return numbers[k - 1]; |
| 41 | + |
| 42 | + function calculatePower(num) { |
| 43 | + let steps = 0; |
| 44 | + while (num !== 1) { |
| 45 | + if (num % 2 === 0) { |
| 46 | + num = num / 2; |
| 47 | + } else { |
| 48 | + num = 3 * num + 1; |
| 49 | + } |
| 50 | + steps++; |
| 51 | + } |
| 52 | + return steps; |
| 53 | + } |
| 54 | + |
| 55 | + function getPower(num) { |
| 56 | + if (!powerValues.has(num)) { |
| 57 | + powerValues.set(num, calculatePower(num)); |
| 58 | + } |
| 59 | + return powerValues.get(num); |
| 60 | + } |
| 61 | +}; |
0 commit comments