Article Directory
1. Source of the subject
Link: 1713. Get the minimum number of operations for the subsequence
2. Topic analysis
Foreword:
A very important knowledge point. When the array elements will not be repeated when the LCS
problem can be transformed into LIS
the problem. LIS
Greedy can reduce the time complexity from O (n 2) O(n^2)O ( n2 )GetO (nlogn) O(nlogn)O ( n- L O G n- ) , comprising the processing10^5
capability of the data range.
But LIS
the greedy wording design to two points, find many of the border. It is recommended to directly back off the board!
- Time complexity : O (nlogn) O(nlogn)O ( n l o g n )。
- Space complexity : O (n) O(n)O ( n )
Code:
class Solution {
public:
int minOperations(vector<int>& target, vector<int>& arr) {
unordered_map<int, int> hash;
for (int i = 0; i < target.size(); i ++ )
hash[target[i]] = i;
vector<int> a;
for (int i = 0; i < arr.size(); i ++ )
if (hash.count(arr[i]))
a.push_back(hash[arr[i]]);
int len = 0;
vector<int> q(a.size() + 1);
for (int i = 0; i < a.size(); i ++ ) {
int l = 0, r = len;
while (l < r) {
int mid = l + r + 1 >> 1;
if (q[mid] < a[i]) l = mid;
else r = mid - 1;
}
len = max(len, r + 1);
q[r + 1] = a[i];
}
return target.size() - len;
}
};