1
+ // Runtime: 98 ms (Top 85.00%) | Memory: 59.9 MB (Top 96.25%)
1
2
class Solution {
2
- public int minOperations (int [] target , int [] arr ) {
3
- int n = target .length ;
4
- Map <Integer , Integer > map = new HashMap <>();
5
-
6
- for (int i = 0 ; i < n ; i ++) {
7
- map .put (target [i ], i );
8
- }
9
-
10
- List <Integer > array = new ArrayList <>();
11
-
12
- for (int i = 0 ; i < arr .length ; i ++) {
13
- if (!map .containsKey (arr [i ])) {
14
- continue ;
15
- }
16
-
17
- array .add (map .get (arr [i ]));
18
- }
19
-
20
- int maxLen = 0 ;
21
- int [] tails = new int [n + 1 ];
22
-
23
- for (int i = 0 ; i < n ; i ++) {
24
- tails [i ] = -1 ;
25
- }
26
-
27
- for (int num : array ) {
28
- int index = findMinIndex (tails , maxLen , num );
29
-
30
- if (tails [index ] == -1 ) {
31
- maxLen ++;
32
- }
33
- tails [index ] = num ;
34
- }
35
-
36
- return n - maxLen ;
37
- }
38
-
39
- public int findMinIndex (int [] tails , int n , int val ) {
40
- int low = 0 ;
41
- int ans = n ;
42
- int high = n - 1 ;
43
-
44
- while (low <= high ) {
45
- int mid = (high + low ) / 2 ;
46
-
47
- if (tails [mid ] >= val ) {
48
- ans = mid ;
49
- high = mid - 1 ;
50
- }
51
- else {
52
- low = mid + 1 ;
53
- }
54
- }
55
- return ans ;
56
- }
3
+ public int minOperations (int [] target , int [] arr ) {
4
+ int n = target .length ;
5
+ Map <Integer , Integer > map = new HashMap <>();
6
+
7
+ for (int i = 0 ; i < n ; i ++) {
8
+ map .put (target [i ], i );
9
+ }
10
+
11
+ List <Integer > array = new ArrayList <>();
12
+
13
+ for (int i = 0 ; i < arr .length ; i ++) {
14
+ if (!map .containsKey (arr [i ])) {
15
+ continue ;
16
+ }
17
+
18
+ array .add (map .get (arr [i ]));
19
+ }
20
+
21
+ int maxLen = 0 ;
22
+ int [] tails = new int [n + 1 ];
23
+
24
+ for (int i = 0 ; i < n ; i ++) {
25
+ tails [i ] = -1 ;
26
+ }
27
+
28
+ for (int num : array ) {
29
+ int index = findMinIndex (tails , maxLen , num );
30
+
31
+ if (tails [index ] == -1 ) {
32
+ maxLen ++;
33
+ }
34
+ tails [index ] = num ;
35
+ }
36
+
37
+ return n - maxLen ;
38
+ }
39
+
40
+ public int findMinIndex (int [] tails , int n , int val ) {
41
+ int low = 0 ;
42
+ int ans = n ;
43
+ int high = n - 1 ;
44
+
45
+ while (low <= high ) {
46
+ int mid = (high + low ) / 2 ;
47
+
48
+ if (tails [mid ] >= val ) {
49
+ ans = mid ;
50
+ high = mid - 1 ;
51
+ }
52
+ else {
53
+ low = mid + 1 ;
54
+ }
55
+ }
56
+ return ans ;
57
+ }
57
58
}
0 commit comments