algorithm - 算法:将元素分布在远离彼此的地方
问题描述
我有一个排序整数数组。给定一个整数 N,我需要将 N 个最大的元素放置得离彼此更远,以便它们之间有最大的空间。其余元素应放在这些大项目之间。例如,N=3 的 10 数组将导致 [0, 5, 8, 2, 6, 9, 3, 7, 10, 4]。
public static void main(String[] args) {
int[] start = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int[] end = new int[10];
int N = 4;
int step = Math.round(start.length / N );
int y = 0;
int count = 0;
for (int i = 0; i < step; i++) {
for (int j = i; j<start.length; j = j + step) {
//System.out.println(j + " " + i);
if (count < start.length && start[count] != 0) {
end[j] = start[count];
count++;
}
}
}
System.out.println(end.toString());
}
解决方案
你有一个K
元素数组。您有N
需要分配的最大数量。然后:
Step := K/N
(删除剩余部分)N
从最大值取任意数字并将其插入Step/2
位置。- 取其他最大数,并在距离上一个插入的最大数之后插入
Step
。
给予[1,2,3,4,5,6,7,8,9,10]
。所以K = 10
,N = 3
。然后Step = 3
。所以第一个最大值放置在3/2
位置
[1,10,2,3,4,5,6,7,8,9]
然后其他2
的彼此3
远离:
[1,10,2,3,9,4,5,8,6,7]
编码:
std::vector<int> Distribute(std::vector<int> aSource, int aNumber)
{
auto step = aSource.size() / aNumber; // Note integer dividing.
for (int i = 0; i < aNumber; ++i)
{
auto place = aSource.end() - i * step - step / 2;
aSource.insert(place, aSource.front());
aSource.erase(aSource.begin());
}
return aSource;
}
int main()
{
std::vector<int> vec{10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10};
auto res = Distribute(vec, 4);
for (auto e : res)
{
std::cout << e << ", ";
}
std::cout << std::endl;
}
输出:
6, 5, 4, 7, 3, 2, 1, 0, 8, -1, -2, -3, -4, 9, -5, -6, -7, -8, 10, -9, -10,
推荐阅读
- visual-studio - 根据事实表列创建新的计算度量
- google-apps-script - 如何将参数传递给回调函数
- elasticsearch - Elasticsearch 7.4 错误地抱怨快照已经在运行
- netty - 如何在netty 1.0.0中监控netty eventloop的队列大小
- protractor - 运行 config.js 时量角器退出并出现错误代码 100
- android - 链接不同 NDK 模块中的原生库
- memory - 保存在上下文中的参数的内存问题
- flutter - 迁移到 Dart 空安全后出现“无法无条件调用运算符,因为接收器可以为空”错误
- flutter - 堆叠架构 - 用户持久性
- sockets - python socket.io 如何发射到特定的客户端?