forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
66 lines (60 loc) · 1.58 KB
/
Solution.java
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
this.c = new int[n + 1];
}
public static int lowbit(int x) {
return x & -x;
}
public void update(int x, int val) {
while (x <= n) {
c[x] = Math.max(c[x], val);
x += lowbit(x);
}
}
public int query(int x) {
int s = 0;
while (x > 0) {
s = Math.max(s, c[x]);
x -= lowbit(x);
}
return s;
}
}
class Solution {
public int minOperations(int[] target, int[] arr) {
Map<Integer, Integer> d = new HashMap<>();
for (int i = 0; i < target.length; ++i) {
d.put(target[i], i);
}
List<Integer> nums = new ArrayList<>();
for (int i = 0; i < arr.length; ++i) {
if (d.containsKey(arr[i])) {
nums.add(d.get(arr[i]));
}
}
return target.length - lengthOfLIS(nums);
}
private int lengthOfLIS(List<Integer> nums) {
TreeSet<Integer> ts = new TreeSet();
for (int v : nums) {
ts.add(v);
}
int idx = 1;
Map<Integer, Integer> d = new HashMap<>();
for (int v : ts) {
d.put(v, idx++);
}
int ans = 0;
BinaryIndexedTree tree = new BinaryIndexedTree(nums.size());
for (int v : nums) {
int x = d.get(v);
int t = tree.query(x - 1) + 1;
ans = Math.max(ans, t);
tree.update(x, t);
}
return ans;
}
}