File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode.cn id=1187 lang=javascript
3
+ *
4
+ * [1187] 使数组严格递增
5
+ */
6
+
7
+ // @lc code=start
8
+ /**
9
+ * @param {number[] } arr1
10
+ * @param {number[] } arr2
11
+ * @return {number }
12
+ */
13
+ var makeArrayIncreasing = function ( arr1 , arr2 ) {
14
+ // 去重+排序
15
+ arr2 = Array . from ( new Set ( arr2 ) ) . sort ( ( a , b ) => a - b ) ;
16
+
17
+ // 初始化dp, dp[i][j] 表示将前 j 个元素通过 i 次替换后变为严格递增序列时, 最后一个元素的最小值
18
+ const dp = new Array ( arr1 . length + 1 ) ;
19
+ for ( let i = 0 ; i < dp . length ; i ++ ) {
20
+ dp [ i ] = new Array ( arr1 . length + 1 ) . fill ( Number . MAX_SAFE_INTEGER ) ;
21
+ }
22
+ dp [ 0 ] [ 0 ] = Number . MIN_SAFE_INTEGER ;
23
+
24
+ for ( let j = 1 ; j < dp . length ; j ++ ) {
25
+ for ( let i = 0 ; i <= j ; i ++ ) {
26
+ if ( arr1 [ j - 1 ] > dp [ i ] [ j - 1 ] ) {
27
+ dp [ i ] [ j ] = arr1 [ j - 1 ] ;
28
+ }
29
+
30
+ // 找到 arr2 中第一个大于 dp[i-1][j-1] 的数
31
+ let a = 0 ;
32
+ let b = arr2 . length - 1 ;
33
+ let t ;
34
+ while ( i > 0 && a <= b ) {
35
+ t = ( a + b ) >> 1 ;
36
+ if ( arr2 [ t ] > dp [ i - 1 ] [ j - 1 ] && ( t - 1 < 0 || arr2 [ t - 1 ] <= dp [ i - 1 ] [ j - 1 ] ) ) {
37
+ break ;
38
+ }
39
+ if ( arr2 [ t ] <= dp [ i - 1 ] [ j - 1 ] ) {
40
+ a = t + 1 ;
41
+ } else {
42
+ b = t - 1 ;
43
+ }
44
+ }
45
+
46
+ // 存在且小于则更新值
47
+ if ( i > 0 && a <= b ) {
48
+ dp [ i ] [ j ] = Math . min ( dp [ i ] [ j ] , arr2 [ t ] ) ;
49
+ }
50
+
51
+ // 返回最终结果
52
+ if ( j == dp . length - 1 && dp [ i ] [ j ] != Number . MAX_SAFE_INTEGER ) return i ;
53
+ }
54
+ }
55
+ return - 1 ;
56
+ } ;
57
+ // @lc code=end
You can’t perform that action at this time.
0 commit comments