简体   繁体   English

将项目分组到一个数组中?

[英]Grouping items in an array?

Hey guys, if I have an array that looks like [A,B,C,A,B,C,A,C,B] (random order), and I wish to arrange it into [A,A,A,B,B,B,C,C,C] (each group is together), and the only operations allowed are: 1)query the i-th item of the array 2)swap two items in the array. 嗨,大家好,如果我有一个看起来像[A,B,C,A,B,C,A,C,B](随机顺序)的数组,我希望将其排列到[A,A,A,B ,B,B,C,C,C](每个组在一起),并且允许的唯一操作是:1)查询数组的第i个项目2)交换数组中的两个项目。

How to design an algorithm that does the job in O(n)? 如何设计在O(n)中起作用的算法?

Thanks! 谢谢!

Sort algorithms aren't something you design fresh (ie first step of your development process) anymore; 排序算法不再是您重新设计(即开发过程的第一步)的东西了。 you should research known sort algorithms and see what meets your needs. 您应该研究已知的排序 算法,然后看看能满足您的需求。

(It is of course possible you might really require your own new sort algorithm, but usually that has different—and highly-specific— requirements .) (当然,您可能确实需要您自己的新排序算法,但通常具有不同的且高度特定的要求 。)

If this isn't your first step (but I don't think that's the case), it would be helpful to know what you've already tried and how it failed you. 如果这不是您的第一步(但事实并非如此),那么了解您已经尝试过的内容以及失败的原因将非常有帮助。

This is actually just counting sort . 这实际上只是计数排序

Scan the array once, count the number of As, Bs, Cs—that should give you an idea. 扫描阵列一次,计算As,Bs和Cs的数量,这应该可以使您有所了解。 This becomes like bucket sort —not quite but along those lines. 这变得像存储桶排序 -不完全是,但遵循这些原则。 The count of As Bs and Cs should give you an idea about where the string of As, Bs and Cs belongs. As Bs和Cs的计数应使您了解As,Bs和Cs字符串所属的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM