【发布时间】:2021-11-19 09:35:24
【问题描述】:
此外,保留两个组中元素的原始相对顺序(即,小于“x”的元素组成一个组,等于或大于“x”的元素组成另一个组。在两个组中都应保持相对顺序。组。)
示例 1:-
a={2,6,3,5,1,7}
x=5
输出:2 3 1 6 5 7
All the elements smaller than 5 come before 5 and the relative order of the moved elements is
preserved (2,3,1) & (6,5,7)
示例 2:-
a={1,4,2,5,3}
x=4
输出:1 2 3 4 5
最初的问题是针对单链表。我为数组编写了算法,我想知道它是否可以移植到链表变体中。另外,有没有更好的方法呢?
#include <bits/stdc++.h>
using namespace std;
void swap(vector<int> &a, int i, int j)
{
int i2 = i;
int x = a[j];
int temp1 = a[i];
int temp2;
while (i < j)
{
temp2 = a[i + 1];
a[i + 1] = temp1;
temp1 = temp2;
i++;
}
a[i2] = x;
}
void solve(vector<int> &a, int num)
{
int n = a.size();
int i = 0, j = 1;
while (j < n)
{
if (a[i] < num)
i++;
if (a[i] >= num && a[j] < num)
swap(a, i, j);
j++;
}
}
int main()
{
vector<int> a = {2, 6, 3, 5, 1, 7};
int num = 5;
solve(a, num);
for (auto el : a)
cout << el << " ";
return 0;
}
【问题讨论】:
-
这在
std中称为partition,并且该站点上的可能实现适用于vector和list(以及其他)。根据具体要求,您可能需要stable_partition -
对于链表,问题实际上比数组更容易。你的算法是 O(n**2);链表有一个 O(n) 简单的解决方案。
-
@infernus-85 实际上,在这种情况下,
using std::cout;会比using namespace std;快。 -
@infernus-85 使用链表,没有“就地”约束;只需将元素添加到两个不同的列表中,具体取决于它们是小于还是大于 x,然后添加一个从“smalls”列表末尾到“larges”列表开头的链接。
标签: c++ arrays algorithm linked-list