数组排列,以使一个数组中的最大元素数更多

编程入门 行业动态 更新时间:2024-10-07 14:28:10
本文介绍了数组排列,以使一个数组中的最大元素数更多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有两个数组A和B(两个元素数量相等)

Assuming I have two arrays A and B (Both with equal number of elements)

int A[] = {40,50,70}; int B[] = {80,60,45};

我必须以数组A中元素的最大数量大于数组B中它们各自的元素的方式重新排列数组A.

I have to rearrange array A in such a way that maximum number of elements in Array A are greater than their respective elements in array B.

在这种情况下,将A重新排列为{40,70,50}将产生所需的结果.

In this case, rearranging A as {40,70,50} would yield the required result.

进行此操作的最佳方法是什么?

What would be the most optimal way of going this?

推荐答案

我会使用类似的东西:

std::vector<int> f(std::vector<int> A, const std::vector<int>& B) { std::vector<std::size_t> indexes(B.size()); std::iota(indexes.begin(), indexes.end(), 0); std::sort(A.begin(), A.end(), std::greater<>{}); std::sort(indexes.begin(), indexes.end(), [&B](std::size_t lhs, std::size_t rhs){ return B[lhs] > B[rhs]; }); auto it = A.begin(); auto rit = A.rbegin(); std::vector<int> res(A.size()); for (auto index : indexes) { if (*it > B[index]) { res[index] = *it; ++it; } else { res[index] = *rit; ++rit; } } return res; }

演示

复杂度: O(n log n).

更多推荐

数组排列,以使一个数组中的最大元素数更多

本文发布于:2023-11-30 07:36:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649195.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:素数   数组   排列   组中   个数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!