|
| 1 | +/* |
| 2 | +Time Complexity: O(nlogn) |
| 3 | +Space Complexity: O(nlogn) |
| 4 | +*/ |
| 5 | +class Solution { |
| 6 | + |
| 7 | + int[] tree; |
| 8 | + int L = 1; |
| 9 | + |
| 10 | + public int lengthOfLIS(int[] nums) { |
| 11 | + init(nums); |
| 12 | + ArrayList<Tuple> tuples = new ArrayList<>(); |
| 13 | + |
| 14 | + for (int i = 0; i < nums.length; i++) { |
| 15 | + tuples.add(new Tuple(i, nums[i])); |
| 16 | + } |
| 17 | + |
| 18 | + Collections.sort(tuples, (a, b) -> { |
| 19 | + if (a.val == b.val) { |
| 20 | + return b.ref - a.ref; // 2순위 : ref 내림차순 |
| 21 | + } else { |
| 22 | + return a.val - b.val; // 1순위 : val 오름차순 |
| 23 | + } |
| 24 | + }); |
| 25 | + |
| 26 | + int ans = 0; |
| 27 | + for (int i = 0; i < nums.length; i++) { |
| 28 | + int curr = getMax(0, tuples.get(i).ref - 1) + 1; |
| 29 | + ans = Math.max(ans, curr); |
| 30 | + insert(tuples.get(i).ref, curr); |
| 31 | + } |
| 32 | + |
| 33 | + return ans; |
| 34 | + } |
| 35 | + |
| 36 | + public class Tuple { |
| 37 | + public int ref; |
| 38 | + public int val; |
| 39 | + |
| 40 | + public Tuple(int ref, int val) { |
| 41 | + this.ref = ref; |
| 42 | + this.val = val; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + public void init(int[] nums) { |
| 47 | + while (L < nums.length) { |
| 48 | + L *= 2; |
| 49 | + } |
| 50 | + |
| 51 | + tree = new int[L * 2]; |
| 52 | + |
| 53 | + for (int i = 1; i < L * 2; i++) { |
| 54 | + tree[i] = 0; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + public void insert(int idx, int v) { |
| 59 | + int i = idx + L; |
| 60 | + tree[i] = v; |
| 61 | + i /= 2; |
| 62 | + while (i >= 1) { |
| 63 | + tree[i] = Math.max(tree[i * 2], tree[i * 2 + 1]); |
| 64 | + i /= 2; |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + public int getMax(int l, int r) { |
| 69 | + int i = l + L; |
| 70 | + int j = r + L; |
| 71 | + int ret = 0; |
| 72 | + while (i <= j) { |
| 73 | + if (i % 2 == 1) { |
| 74 | + ret = Math.max(ret, tree[i++]); |
| 75 | + } |
| 76 | + if (j % 2 == 0) { |
| 77 | + ret = Math.max(ret, tree[j--]); |
| 78 | + } |
| 79 | + i /= 2; |
| 80 | + j /= 2; |
| 81 | + } |
| 82 | + |
| 83 | + return ret; |
| 84 | + } |
| 85 | +} |
0 commit comments