交换两个序列的元素,使元素和的差最小
Swap the elements of two sequences, such that the difference of the element-sums gets minimal.
一个面试问题:
给定两个非有序整数序列
a
和b
,它们的大小为n数是随机选择的:将a
和b
的元素交换,使得a
的元素之和减去b
的元素之总和最小。
举个例子:
a = [ 5 1 3 ]
b = [ 2 4 9 ]
结果是(1+2+3)-(4+5+9)=-12。
我的算法:将它们排序在一起,然后将第一个最小的n
int放在a
中,并将其留在b
中。它在时间上是O(n-lgn),在空间上是0(n)。我不知道如何将其改进为时间为O(n),空间为O(1)的算法。O(1)意味着除了seq1和seq2本身之外,我们不需要更多的额外空间。
有什么想法吗?
另一个问题是:如果我们需要最小化差异的绝对值(最小化|sum(a) - sum(b)|
),该怎么办?
python或C++思维是首选。
修订的解决方案:
-
合并两个列表x=合并(a,b)。
-
计算x的中值(复杂度O(n)参见http://en.wikipedia.org/wiki/Selection_algorithm)
-
使用a和b之间的中值交换元素。也就是说,在a中找到一个小于中值的元素,在b中找到一一个大于中值的元素并交换它们
最终复杂度:O(n)
最小化绝对差是NP完全的,因为它等价于背包问题。
我脑海中浮现的是以下算法大纲:
- C=A对B
- 部分排序#A(A的个数)C的元素
- 从C中减去前#A个元素的和,减去C中最后#B个元素的总和
您应该注意到,不需要对所有元素进行排序,只要找到A最小元素的数量就足够了。举个例子:
- C={5,1,3,2,4,9}
- C={1,2,3,5,4,9}
- (1+2+3)-(5+4+9)=-12
C++解决方案:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
// Initialize 'a' and 'b'
int ai[] = { 5, 1, 3 };
int bi[] = { 2, 4, 9 };
std::vector<int> a(ai, ai + 3);
std::vector<int> b(bi, bi + 3);
// 'c' = 'a' merged with 'b'
std::vector<int> c;
c.insert(c.end(), a.begin(), a.end());
c.insert(c.end(), b.begin(), b.end());
// partitially sort #a elements of 'c'
std::partial_sort(c.begin(), c.begin() + a.size(), c.end());
// build the difference
int result = 0;
for (auto cit = c.begin(); cit != c.end(); ++cit)
result += (cit < c.begin() + a.size()) ? (*cit) : -(*cit);
// print result (and it's -12)
std::cout << result << std::endl;
}
相关文章:
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 我有一系列阵列.可以从一个数组中阅读一些元素和另一个数组中的其他元素
- 在查找子集中元素和元素数量之间的二进制比较背后的逻辑是什么?
- 具有不同类型的元素和使用类的 2D 数组
- 是否可以定义一个宏来定义枚举类和返回枚举元素计数的 GetCount() 方法
- 数组中相邻元素差异的最大和
- 如何在不知道大小的情况下编写过程来修改动态数组的元素和大小
- 如何在不修改现有函数的情况下反转数组中除第一个和最后一个元素之外的所有元素
- 用于随机访问和元素循环的最佳数据结构(C++)
- 字符串和向量<string>元素之间的区别
- 一种按排序顺序保持元素的数据结构,支持快速插入和计算连续元素之间的最大差异
- 使用 std::unique 和 vector.erase 删除除最后一次出现的重复元素之外的所有元素
- 删除已创建的Qt元素和子类
- 将一个元素与具有 8 个具有相同值的元素和 1 个具有不同值的元素的九个元素的数组区分开来
- C++:元素和值这两个术语的意思是一样的吗
- std::unordered_map和由多个元素构建的密钥
- 具有不特定元素大小和元素数量的矢量
- 查找等于给定和的数组元素
- 比较set_intersection(公共元素)的大小和方向使用
- 交换两个序列的元素,使元素和的差最小