|
1 |
| -import java.util.Arrays; |
| 1 | +// https://leetcode.com/problems/ugly-number-iii |
| 2 | +// T: O(log(MAX_VAL)) MAX_VAL = Integer.MAX_VAL here |
| 3 | +// S: O(1) |
2 | 4 |
|
3 | 5 | public class UglyNumberIII {
|
4 |
| - public static int nthUglyNumber(int n, int a, int b, int c) { |
5 |
| - final int[] dp = new int[n + 1]; |
6 |
| - dp[0] = 1; |
7 |
| - int factorA = a, factorB = b, factorC = c; |
8 |
| - int indexA = 0, indexB = 0, indexC = 0; |
| 6 | + private long a; |
| 7 | + private long b; |
| 8 | + private long c; |
| 9 | + private long lcm_a_b; |
| 10 | + private long lcm_a_c; |
| 11 | + private long lcm_b_c; |
| 12 | + private long lcm_a_b_c; |
9 | 13 |
|
10 |
| - for (int i = 1 ; i < dp.length ; i++) { |
11 |
| - final int uglyNumber = min(factorA, factorB, factorC); |
12 |
| - dp[i] = uglyNumber; |
13 |
| - if (uglyNumber == factorA) factorA = a * dp[++indexA]; |
14 |
| - if (uglyNumber == factorB) factorB = b * dp[++indexB]; |
15 |
| - if (uglyNumber == factorC) factorC = c * dp[++indexC]; |
| 14 | + public int nthUglyNumber(int n, int a, int b, int c) { |
| 15 | + setValues(a, b, c); |
| 16 | + int left = 1, right = Integer.MAX_VALUE, middle; |
| 17 | + long factors; |
| 18 | + while (left <= right) { |
| 19 | + middle = left + (right - left) / 2; |
| 20 | + factors = numberOfFactors(middle); |
| 21 | + if (factors >= n) right = middle - 1; |
| 22 | + else left = middle + 1; |
16 | 23 | }
|
17 |
| - System.out.println(Arrays.toString(dp)); |
18 |
| - return dp[dp.length - 1]; |
| 24 | + return left; |
19 | 25 | }
|
20 | 26 |
|
21 |
| - private static int min(int a, int b, int c) { |
22 |
| - return Math.min(a, Math.min(b, c)); |
| 27 | + private void setValues(long a, long b, long c) { |
| 28 | + this.a = a; |
| 29 | + this.b = b; |
| 30 | + this.c = c; |
| 31 | + this.lcm_a_b = lcm(a, b); |
| 32 | + this.lcm_a_c = lcm(a, c); |
| 33 | + this.lcm_b_c = lcm(b, c); |
| 34 | + this.lcm_a_b_c = lcm(lcm_a_b, c); |
23 | 35 | }
|
24 | 36 |
|
25 |
| - public static void main(String[] args) { |
26 |
| - System.out.println(nthUglyNumber(100, 2, 3, 5)); |
| 37 | + /* |
| 38 | + * @param n number |
| 39 | + * @return will tell how many factors are there of a, b and c between 1 and n |
| 40 | + * e.g. if n=10 and a=2 b=3 so there are 7 factors {2, 3, 4, 6, 8, 9, 10} |
| 41 | + */ |
| 42 | + private long numberOfFactors(int n) { |
| 43 | + return n / a |
| 44 | + + n / b |
| 45 | + + n / c |
| 46 | + - n / lcm_a_b |
| 47 | + - n / lcm_a_c |
| 48 | + - n / lcm_b_c |
| 49 | + + n / lcm_a_b_c; |
| 50 | + } |
| 51 | + |
| 52 | + private long gcd(long a, long b) { |
| 53 | + return b == 0 ? a : gcd(b, a % b); |
| 54 | + } |
| 55 | + |
| 56 | + private long lcm(long a, long b) { |
| 57 | + return (a * b) / gcd(a, b); |
27 | 58 | }
|
28 | 59 | }
|
0 commit comments