描述
在原神的幻想世界中,想象有两种不同的神之眼,一种是「目标神眼」(对应target数组),包含一组独一无二的元素;另一种是「现实神眼」(对应arr数组),其可能包含重复元素。你要通过学习「精准调整术」(即在arr数组的任意位置插入任意整数)来完成任务。在「精准调整术」中,你可以选择在「现实神眼」的序列中插入任何整数,从而更接近「目标神眼」的力量。你的目标是找到最少的操作次数,使得「目标神眼」成为「现实神眼」的一个子序列。
输入
输入包括两行,第一行为target数组,第二行为arr数组。
1 <= target.length, arr.length <= 10^4
1 <= target[i], arr[i] <= 10^9
输出
返回最少操作次数
输入样例 1
5 1 3
9 4 2 3 4
输出样例
2
思路:
①The problem can be reduced to computing Longest Common Subsequence between both arrays. ②Since one of the arrays has distinct elements, we can consider that these elements describe an arrangement of numbers, and we can replace each element in the other array with the index it appeared at in the first array. ③Then the problem is converted to finding Longest Increasing Subsequence in the second array, which can be done in O(n log n).
代码实现:
方法1:动态规划与暴力查找
#include<iostream>
#include<string>
#include<sstream>
#include<vector>
using namespace std;
void input(vector<int>& v);
class solution
{
public:
int minOperations(vector<int>& target,vector<int>& arr)
{
vector<int> v;
for(int i=0;i<arr.size();i++)
{
int j;
for(j=0;j<target.size();j++)
{
if(arr[i]==target[j])break;
}
if(j==target.size())continue;
else v.push_back(j);
}
int res=LIS(v);
return res;
}
int LIS(vector<int>& v)
{
int m=0,n=v.size();
vector<int> dp(n,0);
for(int i=0;i<n;i++)
{
dp[i]=1;
for(int j=i-1;j>=0;j--)
{
if(v[j]<v[i])
{
dp[i]=max(dp[i],dp[j]+1);
}
}
if(dp[i]>m)m=dp[i];
}
return m;
}
};
int main()
{
vector<int> target,arr;
input(target);
input(arr);
solution p;
int len=p.minOperations(target,arr);
cout<<target.size()-len<<endl;
return 0;
}
void input(vector<int>& v)
{
string line;
getline(cin, line);
istringstream iss(line);
int num;
while (iss >> num) {
v.push_back(num);
}
}
方法2:贪心算法与哈希查找
class Solution {
public:
int minOperations(vector<int> &target, vector<int> &arr) {
int n = target.size();
unordered_map<int, int> pos;
for (int i = 0; i < n; ++i) {
pos[target[i]] = i;
}
vector<int> d;
for (int val : arr) {
if (pos.count(val)) {
int idx = pos[val];
auto it = lower_bound(d.begin(), d.end(), idx);
if (it != d.end()) {
*it = idx;
} else {
d.push_back(idx);
}
}
}
return n - d.size();
}
};
贪心法获得最长上升子序列