最长公共子序列转化为最长上升子序列

leetcode https://leetcode.com/problems/minimum-operations-to-make-a-subsequence/

Weekly Contest 222

1713. Minimum Operations to Make a Subsequence

You are given an array target that consists of distinct integers and another integer array arr that can have duplicates.

In one operation, you can insert any integer at any position in arr. For example, if arr = [1,4,1,2], you can add 3 in the middle and make it [1,4,3,1,2]. Note that you can insert the integer at the very beginning or end of the array.

Return the minimum number of operations needed to make target a subsequence of arr.

subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order. For example, [2,7,4] is a subsequence of [4,2,3,7,2,1,4] (the underlined elements), while [2,4,2] is not.

 

Example 1:

Input: target = [5,1,3], arr = [9,4,2,3,4]
Output: 2
Explanation: You can add 5 and 1 in such a way that makes arr = [5,9,4,1,2,3,4], 
then target will be a subsequence of arr.

Constraints:

  • 1 <= target.length, arr.length <= 105
  • 1 <= target[i], arr[i] <= 109
  • target contains no duplicates.

 

 

    public int minOperations(int[] target , int[] arr) {
        Map<Integer, Integer> map = new HashMap();
        int n = target.length, m = arr.length;
        for(int i = 0; i < n; i++){
            map.put(target[i], i + 1);
        }
        int[] arr2 = new int[m + 1];
        for(int i = 0; i < m; i++){
            if(map.containsKey(arr[i])){
                arr2[i + 1] = map.get(arr[i]);
            }
        }

        List<Integer> list = new ArrayList();
        for(int i = 1; i <= m; i++){
            if(arr2[i] == 0) continue;
            if(list.isEmpty() || arr2[i] > list.get(list.size() - 1)){
                list.add(arr2[i]);
            }else{
                int l = 0, r = list.size() - 1;
                while(l < r){
                    int mid = l + r >> 1;
                    if(list.get(mid) >= arr2[i]) r = mid;
                    else l = mid + 1;
                }
                list.set(l, arr2[i]);
            }
        }
        return n - list.size();
    }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值