我想这是个非常新鲜的问题,但我已经花了6个多小时这样做了,我不知道最好的方法是什么,所以我请求你帮助我如何完成这个任务。
我有两本书,例如汽车和自行车。我必须制造list或array (我不知道哪个更好),它的内部有2-1000个元素,当它完成后,我必须重新订购list/array (自行车在开始,汽车在最后)。这里只有一辆自行车和一辆汽车,但也可能有几百辆、甚至更多的自行车。我不知道是否有可能使EnumMap大约两个枚举。
EnumMap有键和值,所以我给出了键" car“和值"0",以及键”自行车“值"1",这样可以更容易地重新排序,但是我发现在EnumMap上不能这样做,因为不管我添加了多少元素,总是只有2,自行车和car。我不想在那里谈论几百人。
我之所以没有专注于数组,是因为在代码的开头有enum garage {bike, car};
这是家庭作业,是的,但我只是希望找到方法(花几个小时只是阅读和尝试不同的方法),而不是有人为我这样做。
发布于 2014-09-13 01:31:37
我建议你把逻辑分成两种方法,第一种是countGoats(Animal[]) -
private static int countGoats(Animal[] animals) {
int count = 0;
for (Animal a : animals) {
if (Animal.goat == a) {
count++;
}
}
return count;
}由于到goats计数为止的每个元素都应该是数组中的一个goat (以及sheep之后的每个元素),所以我们可以使用类似的方法来迭代数组,
public static void reorder(Animal[] animals) {
if (animals == null) {
return;
}
int goats = countGoats(animals);
for (int i = 0; i < animals.length; i++) {
// if (i < goats) - it's a goat, otherwise it's a sheep.
animals[i] = (i < goats) ? Animal.goat : Animal.sheep;
}
}这是一个计数排序的例子,运行时复杂度为O(n)。正如维基百科文章所指出的,
因为计数排序使用键值作为数组中的索引,所以它不是比较排序,比较排序的Ω(n log )下限不适用于它。
发布于 2014-09-13 01:06:17
好吧,根据我的理解。您需要有一个List of Animals,并实现一个方法public static void reorder(ArrayList<Animal> animals)来重新排序这个列表。
这就是我想出来的:
public class EnumHw {
public static void main(String[] args) {
ArrayList<Animal> animalList = new ArrayList<Animal>();
animalList.add(Animal.GOAT);
animalList.add(Animal.SHEEP);
animalList.add(Animal.GOAT);
animalList.add(Animal.SHEEP);
EnumHw.reorder(animalList);
for (Animal animal : animalList) {
System.out.println(animal);
}
}
public static void reorder(ArrayList<Animal> animals) {
Collections.sort(animals);
}
}
enum Animal {
//Order you enum in the way you want them to come first in the List
GOAT,
SHEEP;
}希望它能帮助您(并且允许您使用Collections API。:)
发布于 2014-09-13 01:05:39
public void reorder(Animal[] animals) {
int sheepCount = 0;
int goatCount = 0;
for (Animal oneAnimal : animals) {
if (oneAnimal == Animal.sheep) {
sheepCount++;
} else {
goatCount++;
}
}
for (int i = 0; i < sheepCount; i++) {
animals[i] = Animal.sheep;
}
for (int i = 0; i < goatCount; i++) {
animals[i + sheepCount] = Animal.goat;
}
} https://stackoverflow.com/questions/25818720
复制相似问题