C++ 数组排列,使其具有来自另一个数组的较小值
在本教程中,我们得到了两个数组 A 和 B。例如,我们需要输出 A 的任何排列,以便最大化 A[I] > B[I] 的索引,例如
Input: A = [12, 22, 41, 13], B = [1, 20, 10, 12] Output: 12, 22, 41, 13 Input: A = [2, 5, 9, 7], B = [1, 12, 4, 54] Output: 2 7 5 9 Multiple answers can be present in that case we are simply going to print any one of the answers.
在这个问题中,我们需要最大化 A[i] > B[i] 的索引,所以我们将贪婪地解决这个问题。
查找解决方案的方法
在这种方法中,我们将首先对这两个数组进行排序;我们贪婪地检查数组 B 的每个索引,使得 A[i] 比它更重要,然后将该元素放入向量中。
示例
#include <bits/stdc++.h>
using namespace std;
int main(){
int A[] = { 2, 5, 9, 7 };
int B[] = { 1, 12, 4, 54 };
int n = sizeof(A) / sizeof(int); // size of our arrays
vector<pair<int, int> > A_pair, B_pair;
/***********************We are linking element to its position***********/
for (int i = 0; i < n; i++)
A_pair.push_back({A[i], i});
for (int i = 0; i < n; i++)
B_pair.push_back({B[i], i});
/***********************************************************************/
/*****Sorting our pair vectors********************/
sort(A_pair.begin(), A_pair.end());
sort(B_pair.begin(), B_pair.end());
int i = 0, j = 0, ans[n];
memset(ans, -1, sizeof(ans)); // initializing all the elements with value -1
vector<int> remaining; // this will store our elements which have lesser value than elemnt present in B.
while (i < n && j < n) {
// as our array is sorted then if we find any element in
//current index which has less value than B of current index then
// automatically it will have less value than other elements of B
// that's why we push such indices in remaining otherwise we push element in ans
if (A_pair[i].first > B_pair[j].first) {
ans[B_pair[j].second] = A_pair[i].first;
i++;
j++;
}
else {
remaining.push_back(i);
i++;
}
}
j = 0;
for (int i = 0; i < n; ++i){
// now if any index of answer is unchanged so that means
//we need to fill that position with the remaining elements
if (ans[i] == -1){
ans[i] = A_pair[remaining[j]].first;
j++;
}
}
for (int i = 0; i < n; i++) // printing our answer
cout << ans[i] << " ";
return 0;
}输出
2 7 5 9
以上代码的解释
在这种方法中,我们首先将所有元素与其索引关联起来,以便在排序时仍然保留其旧索引。我们对这两个元素对的向量进行排序,现在我们贪婪地搜索我们的答案,当我们遍历这两个数组时,如果我们得到 A_pair 的索引,其值大于 B_pair 的值,那么我们将它存储在我们的数组中(以及在 B_pair 的位置),否则,因为我们已经对这两个向量进行了排序,所以我们知道我们将无法使用这个 A_pair 的值,所以我们将该元素的索引推入我们的剩余向量中,现在我们借助剩余向量填充数组,然后我们打印答案。
结论
在本教程中,我们解决了一个问题,即查找一个数组的排列,该数组具有来自另一个数组的较小值。我们还学习了这个问题的 C++ 程序以及我们解决的完整方法。我们可以用其他语言(如 C、Java、Python 和其他语言)编写相同的程序。我们希望您觉得本教程有所帮助。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP