开发者

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.

How to design an algorithm that does the job in O(n)?

Thanks!


Sort algorithms aren't something you design fresh (i.e. 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. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜